vue.js

[vue.js] componentの親子間データやり取り

子HelloWirld.vue => 親App.vue

子のプロパティーにバインドして、値を渡す。

App.vue
<template>
<div id="app">
<img alt="Vue logo" src="./assets/logo.png">
<HelloWorld msg="Welcome to Your Vue.js App"
v-bind:change_from_app="message"
v-on:result-event="appAction"
/>
<hr>
<button v-on:click="doAction">change title</button>
<p>{{ result }}</p>

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

export default {
name: 'app',
components: {
HelloWorld
},
data: function(){
return{
message:'HELLO',
result:'no event',
}
},
methods:{
doAction: function(){
var _in = prompt("new title");
this.message = _in;
},
appAction: function(_msg){
this.result = '(*** you send: )' + _msg + ' ***)';
}
}
}
</script>
HelloWorld.vue
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<p>{{ tx_msg }}</p>
<p>{{ change_from_app }}</p>

<div>
<input type="text" v-model="tx_input" >
<button v-on:click="doClicked">click</button>
</div>

</div>
</template>

<script>
export default {
name: 'HelloWorld',
props: {
msg: String,
change_from_app: String
},
data: function(){
return {
tx_msg: 'what\'s your name?',
tx_input: 'no name',
};
},
methods: {
doClicked: function(){
this.tx_msg = 'hello '+ this.tx_input;

//send msg to App component.
this.$emit('result-event', this.tx_input);
},
}
}
</script>

親App.vue=>子HelloWirld.vue 
HelloWirld.vue
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<p>{{ tx_msg }}</p>
<p>{{ change_from_app }}</p>

<div>
<input type="text" v-model="tx_input" >
<button v-on:click="doClicked">click</button>
</div>

</div>
</template>

<script>
export default {
name: 'HelloWorld',
props: {
msg: String,
change_from_app: String
},
data: function(){
return {
tx_msg: 'what\'s your name?',
tx_input: 'no name',
};
},
methods: {
doClicked: function(){
this.tx_msg = 'hello '+ this.tx_input;

//send msg to App component.
this.$emit('result-event', this.tx_input);
},
}
}
</script>

App.vue
<template>
<div id="app">
<img alt="Vue logo" src="./assets/logo.png">
<HelloWorld msg="Welcome to Your Vue.js App"
v-bind:change_from_app="message"
v-on:result-event="appAction"
/>
<hr>
<button v-on:click="doAction">change title</button>
<p>{{ result }}</p>

</div>
</template>

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

export default {
name: 'app',
components: {
HelloWorld
},
data: function(){
return{
message:'HELLO',
result:'no event',
}
},
methods:{
doAction: function(){
var _in = prompt("new title");
this.message = _in; // set message, binded change_from_app property changed.
},
appAction: function(_msg){
this.result = '(*** you send: )' + _msg + ' ***)';
}
}
}
</script>

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です