Vue组件使用基础
这篇博文用来记录 .vue 组件的使用方法。
可以把组件代码按照 template、style、script 的拆分方式,放置到对应的 .vue 文件中。
模板(template)、初始数据(data)、接受的外部参数(props)、方法(methods)、生命周期钩子函数(lifecycle hooks)。
基本步骤
在 html 中使用组件
<div id="app">
<my-component></my-component>
</div>
使用组件首先需要创建构造器:
var myComponent = Vue.extend({
template: `<p>myComponent</p>`
})
要把这个构造器用作组件,需要用 Vue.component(tag, constructor) 注册 :
全局注册
// 全局注册组件,tag 为 my-component
Vue.component('my-component', myComponent)
Vue.component('my-component', MyComponent)这种是全局注册,第一个参数是注册组件的名称,第二个参数是组件的构造函数;
选项对象的template属性用于定义组件要渲染的HTML;
局部注册
new Vue({
el: '#app',
components: {
'my-component': myComponent
}
})
子组件只能在父组件的template中使用。
组件选项问题
在定义组件的选项时,data 和 el 选项必须使用函数。
如果data选项指向某个对象,这意味着所有的组件实例共用一个data。
所以应当使用一个函数作为 data 选项,让这个函数返回一个新对象:
Vue.component('my-component', {
data: function () {
return {a: 1}
}
});
同理,el 选项用在 Vue.extend() 中时也须是一个函数。
数据传递
Vue.js组件之间有三种数据传递方式:
- props
- 组件通信
- slot
props
props是组件数据的一个字段,期望从父组件传下来数据。因为组件实例的作用域是孤立的,所以子组件需要显式地用props选项来获取父组件的数据。
props选项可以是字面量、表达式、绑定修饰符。
字面量
<div id="app">
<child msg="hello!"></child>
</div>
<script src="https://cdn.bootcss.com/vue/2.4.4/vue.js"></script>
<script>
Vue.component('child', {
props: ['msg'],
// prop 可以用在模板内
// 可以用 this.msg 设置
template: `<span>{{msg}} Are you tired?</span>`
});
new Vue({
el: "#app"
})
</script>
HTML 特性不区分大小写。名字形式为 camelCase 的 prop 用作特性时,需要转为 kebab-case(短横线隔开):
<div id="app">
<child my-message="hello!"></child>
</div>
<script src="https://cdn.bootcss.com/vue/2.4.4/vue.js"></script>
<script>
Vue.component('child', {
props: ['myMessage'],
template: `<span>{{myMessage}} Are you tired?</span>`
});
new Vue({
el: "#app"
})
</script>
动态
用 v-bind 绑定动态 props 到父组件的数据。每当父组件的数据变化时,也会传导给子组件。
<div id="app">
<input v-model="parentMsg"><br>
<child :my-message="parentMsg"></child>
</div>
<script src="https://cdn.bootcss.com/vue/2.4.4/vue.js"></script>
<script>
Vue.component('child', {
props: ['myMessage'],
template: `<span>{{myMessage}} Are you tired?</span>`
});
new Vue({
el: "#app",
data: {
parentMsg: 'hello!'
}
})
</script>
绑定类型
可以使用绑定修饰符:
.sync,双向绑定.once,单次绑定
<!-- 默认为单向绑定 -->
<child :msg="parentMsg"></child>
<!-- 双向绑定 -->
<child :msg.sync="parentMsg"></child>
<!-- 单次绑定 -->
<child :msg.once="parentMsg"></child>
prop 默认是单向绑定:当父组件的属性变化时,将传导给子组件,但是反过来不会。
不过需要注意的是:如果 prop 是一个对象或数组,是按引用传递。在子组件内修改它会影响父组件的状态,不管是使用哪种绑定类型。
prop类型验证
Vue.component('example', {
props: {
propA: Number,// 基础类型检测 (`null` 任何类型)
propM: [String, Number],// 多种类型 (1.0.21+)
propB: {// 必需且是字符串
type: String,
required: true
},
propC: {// 数字,有默认值
type: Number,
default: 100
},
propD: {// 对象|数组的默认值应当由一个函数返回
type: Object,
default: function () {
return {msg: 'hello'}
}
},
propE: {
// 指定这个 prop 为双向绑定
// 如果绑定类型不对将抛出一条警告
twoWay: true
},
propF: {// 自定义验证函数
validator: function (value) {
return value > 10
}
},
propG: {
// 转换函数(1.0.12 新增)
// 在设置值之前转换值
coerce: function (val) {
return val + '';// 将值转换为字符串
}
},
propH: {
coerce: function (val) {
return JSON.parse(val);// 将 JSON 字符串转换为对象
}
}
}
});

浙公网安备 33010602011771号