vue子组件改变父组件值--写法1

1、父:要点

  1. 正常父传子
    :msg="oldValue"
  2. 正常子接父
    @iClick="yClick"
<template>
<div id="app">
<HelloWorld @iClick="yClick" :msg="oldValue"/>
</div>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'

export default {
name: 'App',
components: {
HelloWorld
},
methods: {
yClick (value) {
this.oldValue = value
}
},
data () {
return {
oldValue: 'oldValue'
}
}
}
</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>

2、子:要点

  1. 在data中将接收到的props值重新赋值
    childMsg: this.msg
  2. 将v-model拆分
    :value="childMsg" @input="changeMsg"
  3. 正常子传父
    this.$emit('iClick', this.childMsg)
<template>
<div class="hello">
<h1>msg-props==={{ msg }}</h1>
<h1>childMsg-data==={{ childMsg }}</h1>
<input type="text" :value="childMsg" @input="changeMsg" />
</div>
</template>

<script>
export default {
name: 'HelloWorld',
props: {
msg: {
type: String
}
},
data () {
return {
childMsg: this.msg
}
},
methods: {
changeMsg (event) {
this.childMsg = event.target.value
this.$emit('iClick', this.childMsg)
}
}
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
margin: 40px 0 0;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>
上一篇:vue子组件改变父组件值--写法2


下一篇:C# Replace方法