系列文章目录
提示:vue基础知识总结
前言
v-model 和 .sync 原理
v-model 和 .sync 都是语法糖,本质上还是父子组件通信
父传子: Props Down
子传父 Events UP
<template>
<div>
<h1>
Parent Component
</h1>
<p>{{message}}</p>
<p>{{foo}}</p>
<!-- Props Down 给子组件传值 -->
<!-- <Child :message="message"
@change-message="message = $event"
/> -->
<!-- 当你需要子组件同步一个数据的时候:
子组件既要使用这个数据
子组件还要修改这个数据
以前你肯定需要通过 Props Down 和 Events Up 来实现,现在为了方便,
提供了一个特殊的语法糖: v-mode
v-model="message" 语法糖
:value="message" Props Down
@input="message = 事件参数"
-->
<!-- <Child v-model = "message" /> -->
<!-- 在一个组件上只能使用一次 v-model,如果你想要对多个数据同步绑定,
则可以使用 .sync 修饰符。
.sync 也是一个语法糖
:foo = "foo" Props Down 传递数据
@update:foo = "foo = 事件参数" 自定义事件
-->
<Child v-model = "message" :foo.sync="foo"/>
</div>
</template>
<script>
import Child from './Child'
export defalut {
name: 'ParentComponent',
components: {
Child
},
data () {
return {
message:'Parent message',
foo:'Parent foo'
}
}
}
</script>
<style>
</style>
<template>
<div>
<h1>
Child Component
</h1>
<!-- <p> {{message}}</p> -->
<p> {{ value }}</p>
<button @click='handleChange'>修改 message</button>
<p> {{ foo }}</p>
<button @click='$emit('update:foo','Child foo')'>修改 foo </button>
<Child />
</div>
</template>
<script>
export defalut {
name: 'ChildComponent',
//Props 是单向数据流 子组件只能读取,不能修改(对象类型可以,不建议修改)
props: {
// 接受 v-model 传递的Props 数据
value: {
type:String
},
foo: {
type: String
}
// message: {
// type:String
// }
},
methods: {
handleChange(){
// this.message = 'Child message';
子组件给父组件发布 自定义事件: Events Up
// this.$emit('change-message','child message');
this.$emit('input','child message');
}
}
}
</script>
<style>
</style>
v-model 和 .sync 区别?
相同点:都是语法糖,都可以实现父子组件中的数据的双向绑定。
区别点:格式不同:v-model=“message”, :foo.sync=“foo”
v-model 和 .sync我们怎么选择?
v-model 和 .sync 的作用是一样的,到底用哪个?
如果有且仅有一个数据需要双向绑定:v-model, 习惯问题。
如果有多个数据需要和子组件同步绑定:
可以把最主要的设置为 v-model 把其他的设置为 .sync 修饰符
所有组件上监听的事件都是自定义事件