vue中v-bind修饰符.sync和.once没效果

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>v-bind onece sync用法</title>

</head>

<body>

<div id="example">

<input type="text" v-model="msg">

<child :msg.sync="msg"></child>

</div>

<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/vue"></script>

<script type="text/javascript">

var child = Vue.extend({

props: ['msg'],

template: '<div><button v-on:click="changeChildMsg">click</button><p>{{msg}}</p></div>',

methods: {

changeChildMsg () {

this.msg = 'Hello Vue!'

}

}

})

var vm = new Vue({

el: '#example',

data () {

return {

msg: 'wang wang wang!'

}

},

components: {

child: child

}

})

</script>

</body>

</html>

Vue文档说明.sync能让子组件数据和父组件数据进行双向绑定。可为何当点击子组件中click按钮后,vm.msg还是wang wang wang!

回答:

vue的文档里写的很清楚:
从 2.3.0 起我们重新引入了 .sync 修饰符,但是这次它只是作为一个编译时的语法糖存在。它会被扩展为一个自动更新父组件属性的 v-on 监听器。
如下代码
<comp :foo.sync="bar"></comp>
会被扩展为:
<comp :foo="bar" @update:foo="val => bar = val"></comp>
当子组件需要更新 foo 的值时,它需要显式地触发一个更新事件:
this.$emit('update:foo', newValue)

因此你的

changeChildMsg () {

this.msg = 'Hello Vue!'

}

改成

changeChildMsg () {

this.$emit('update:msg', "hello")

}

回答:

图片描述vue2.0已经移除v:bind的.sync和.once

以上是 vue中v-bind修饰符.sync和.once没效果 的全部内容, 来源链接: utcz.com/a/149831.html

回到顶部