vue-05-vue组件

vue组件

啥是组件?为了拆分vue实例的代码量,能够让我们以不同的组件,来划分不同的功能模块,将来需要什么样的功能,就去调用对应的组件 。

组件化和模块化的不同:

  • 模块化:按照代码逻辑来划分成不同的模块,方便代码分层开发,保证每个模块功能的单一。
  • 组件化:按照UI界面进行划分,方便UI组件的重用。

创建组件的3种方式

  • 1
    2
    3
    Vue.componemt('mycom1', Vue.extend({
    template: '<h3>这是一个组件</h3>'
    }))
  • 1
    2
    3
    Vue.component('mycom2', {
    template: '<div></div>'
    })
  • 1
    2
    3
    4
    5
    6
    7
    8
    <template id="tmpl">
    <div></div>
    </template>
    <script>
    Vue.component('mycom2', {
    template: '#tmpl'
    }
    </script>

创建私有组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<template id="login">
<div>
一个私有组件
</div>
</template>

<script>
var vm = new Vue({
el: '#app',
data: {},
methods: {},
components: {
login: {
template: '#login'
}
},
filters: {},
directives: {},

beforeCreate () {},
})
</script>

组件中的data

组件中的data必须写成function形式,并且得返回一个对象

1
2
3
4
5
6
7
8
Vue.component('mycom', {
template: '<h1>{{ msg }}</h1>',
data: function () {
return {
msg: 'helloworld'
}
}
})

组件切换

除了v-if v-else外,用component标签占位可以来实现切换

1
2
3
4
5
6
<component :is="'login'"></component> //双引号里必须是字符串,要不然会把它看成变量
<script>
Vue.component('login', {
template: '<h3>deng'lu</h3>'
})
</script>

组件切换加动画和mode

mode=”out-in”先出后进 in-out 先进后出

1
2
3
<transition mode="out-in">
<component :is="comName"></component>
</transition>

父组件向子组件传值

在子组件上绑定父属性

用props注册传过来的值的名(注意命名)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<div id="app">
<son :parentmsg="msg" :tip="msg2"></son>
</div>
<script>
var vm = new Vue({
el: '#app',
data: {
msg: 'helloworld',
msg2: '命名还有讲究'
},
methods: {

},
components: {
son: {
template: '<h3>i want to say {{ parentmsg }} {{ tip }}</h3>',
props: ['parentmsg', 'tip']
}
}
})
</script>

父组件向子组件传方法

先创建子组件

使用子组件时,给来自父组件的方法起个别名sonfunc

使用this.$emit(‘别名’,第一个形参,第二个形参)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<div id="app">
<son @sonfunc="fatherfunc"></son>
</div>
<template id="son">
<input type="button" value="show" @click="myclick">
</template>
<script>
var vm = new Vue({
el: '#app',
data: {
msg: 'helloworld',
msg2: '命名还有讲究'
},
methods: {
fatherfunc(a, b) {
console.log('fatherfunc 被调用'+' '+a+b)
}
},
components: {
son: {
template: '#son',
props: ['parentmsg', 'tip'],
methods: {
myclick() {
this.$emit('sonfunc', '第一个参数', '第二个参数')
}
}
}
}
})
</script>

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×

// tidio机器人助手