1. 程式人生 > 其它 >vue子元件改變父元件值--寫法1

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>