vue.js官方教程上讲的也挺清楚的了,本身整理一遍以加深印象,同时也完成本身的项目中须要的动态建立表单提交编辑修改功能。
表单主要是v-model双向绑定实现父组件与子组件的双向数据传递,因此首先说一下组件之间的通讯。vue
// 子组件
Vue.component("my-com",{
template:"<div>{{msg}}===={{info}}</div>",
props:["msg"], //必须是字符串形式
data:function(){
return {
info:"子组件的信息"
}
}
});
// 使用时
<my-com :msg="message"></my-com> // 必须使用v-bind绑定,否则传递的是字符串
var app=new Vue({
el:"#app",
data:{
message:"父组件的内容"
}
});
复制代码
//逻辑是,给子组件添加事件,子组件事件触发时,往上触发父组件的事件,而且给事件传值,父组件便可得到子组件的值并在事件中处理
Vue.component("my-com",{
template:'<button type="button" @click="add">点击+1</button>',
data:function(){
return {
count:0
}
},
methods:{
add(){
this.count++;
this.$emit("from-son",this.count);
}
}
})
// 使用时
<my-com @from-son="add1"></my-com> // 触发from-son事件,接收到子组件的数据
var app=new Vue({
el:"#app",
data:{
msg:""
},
methods:{
add1(value){
this.msg=value;
}
}
})
复制代码
由前面分析能够看出,实现双向绑定的话,就是同时有props传递,又有$emit()触发
首先,<input v-model="text">
等价于:bash
<input v-bind:value="text" v-on:input="text=$event.target.value">
复制代码
所以组件要使用v-model,也须要:app
<my-component
v-bind:value="text" //父向子传递
v-on:input="text=$event.target.value" //子向父传递
><my-component>
复制代码
因此子组件必须知足:ui
Vue.component("my-component",{
template:'<div @click="fn"></div>'
props:['value'],
methods:{
fn(event){
this.$emit("input",event.target.value)
}
}
})
复制代码