Vue中父组件向子组件传递数据的时候,子组件中通常使用props定义变量接收,当子组件想要修改这个接收的变量的时候,往往都是要通过 子组件定义事件 this.$emit()的方式向父组件发送事件,而父组件则需要在methods中定义变量去接收响应这个事件,这样的传输方式往往比较复杂,而且不够优雅!那么sync修饰符就可轻松解决这个问题。
这次演示没有使用单文件组件
什么是sync同步修饰符?
在vue中 通过props传递参数是单项数据流,被传递的参数只能被父组件所修改,sync修饰符就可以将变量修改为与子组件同步修改该变量的模式
我们先来看看没有sync修饰符时,父子组件该如何进行参数修改。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>vue sync修饰符</title>
<script src="./vue文件/vue.min.js"></script>
</head>
<body>
<div id="app">
<cnp @changes="fu_change" :one="mas"></cnp>
</div>
<template id="one">
<div>
<h1>{{one}}</h1>
<button v-on:click="change">点击修改props内的值</button>
</div>
</template>
<script>
// 在不适用 async修饰符的时候 传统子组件想要修改父组件的中的值 需要用到this.$emit() 发送自定义事件 并在父组件中触发该事件
// 但是 当子组件标签中 绑定的值 加上async时 则 只需要在子组件中 methods 中的方法添加 this.$emit("update:+想要修改的props值","目标值")
// 父组件中并不需要定义事件接收 这样提高了开发效率 节省代码量
const app = new Vue({
el:"#app",
data() {
return {
mas:"我是父组件中的数据"
}
},
methods: {
fu_change(e){
this.mas = e;
}
},
components:{
cnp:{
template:"#one",
data() {
return {
mgg:"我是子组件修改后的值"
}
},
props:["one"],
methods: {
change(){
this.$emit("changes",this.mgg)
}
},
}
}
})
//this.$emit("update:one",this.mgg)
</script>
</body>
</html>
效果
修改前:
修改后:
我们可以看到,文字被修改成功了,
那么使用async呢?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>vue sync修饰符</title>
<script src="./vue文件/vue.min.js"></script>
</head>
<body>
<div id="app">
<cnp :one.sync="mas"></cnp>
</div>
<template id="one">
<div>
<h1>{{one}}</h1>
<button v-on:click="change">点击修改props内的值</button>
</div>
</template>
<script>
// 在不适用 async修饰符的时候 传统子组件想要修改父组件的中的值 需要用到this.$emit() 发送自定义事件 并在父组件中触发该事件
// 但是 当子组件标签中 绑定的值 加上async时 则 只需要在子组件中 methods 中的方法添加 this.$emit("update:+想要修改的props值","目标值")
// 父组件中并不需要定义事件接收 这样提高了开发效率 节省代码量
const app = new Vue({
el:"#app",
data() {
return {
mas:"我是父组件中的数据"
}
},
// methods: {
// fu_change(e){
// this.mas = e;
// }
// },
components:{
cnp:{
template:"#one",
data() {
return {
mgg:"我是子组件修改后的值"
}
},
props:["one"],
methods: {
change(){
this.$emit("update:one",this.mgg)
}
},
}
}
})
//this.$emit("update:one",this.mgg)
</script>
</body>
</html>
效果
修改前:
修改后:
由上面可见 ,添加了async后 ,父组件不再定义事件即可在子组件中修改props中的值
总结:
async的用法: :绑定值.sync=”目标值“
在组件中 this.$emit("update:'props内的值'",修改目标值)
update是定义的关键字,不可修改。
本次分享就到这了,希望能帮到你!