常规情况下,我们进行子向父更新值得时候都需要这样做
<template>
<div id="app">
<hello-world :value="value" @change="changeValue"></hello-world>
</div>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue'
export default {
name: 'App', //父组件
components: {
HelloWorld,
},
data(){
return{
value:''
}
},
methods:{
changeValue(e){
this.value = e
}
}
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
<template>
<div class="hello">
<input
placeholder="placeholder"
v-bind:value="value"
>
<br>
<button @click="change">change</button>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
props: ['value'],
data(){
return {
}
},
methods:{
change(){
this.$emit('change', '常规子向父更新值')
}
}
}
</script>
<style scoped>
</style>
使用sync修饰符实现子向父更新值
<template>
<div id="app">
<hello-world :value.sync="value"></hello-world>
</div>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue'
export default {
name: 'App', //父组件
components: {
HelloWorld,
},
data(){
return{
value:''
}
},
methods:{
}
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
<template>
<div class="hello">
<input
placeholder="placeholder"
v-bind:value="value"
>
<br>
<button @click="change">change</button>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
props: ['value'],
data(){
return {
}
},
methods:{
change(){
this.$emit('update:value','我是由vue修饰符.sync改变的')
}
}
}
</script>
<style scoped>
</style>
网友评论