Issue
Here I have two components:
msg.vue
<template>
<div>
<input type="text" v-model="msg" />
</div>
</template>
<script>
export default {
name: "msg",
props: ["msg"]
};
</script>
samples.vue
<template>
<div>
<h2>{{ msg }}</h2>
</div>
</template>
<script>
export default {
name: "samples",
props: ["msg"]
};
</script>
and finally,
App.vue
<template>
<div id="app">
<samples v-bind:msg="msg"></samples>
<msg :msg="msg"></msg>
</div>
</template>
<script>
import samples from "./components/samples.vue";
import msg from "./components/msg.vue";
export default {
name: "app",
components: {
samples,
msg
},
data: () => {
return {
msg: "Hello World"
};
}
};
</script>
<style>
#app {
font-family: "Poppins", Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
margin-top: 60px;
}
</style>
The thing I want to do is with the msg
component I want to change the msg
component in the data of App.vue. But when I change the value, Vue warns this :
So I can't understand what to do next. Please help me in this.
Solution
1. What's v-model
?
<input v-model="msg" />
basically will transpile to
<input :value="msg" @input="msg = $event.target.value" />
2. data
vs props
2.1 data
is supposed to be component self-contained, whereas props
is passed from parents.
2.2 data
should be mutable within the component, props
shouldn't. Why? Because of 2.1.
3. mutating a prop locally is considered an anti-pattern in Vue 2
Result: Here's the solution that I changed only 2 lines of code from yours:
App.vue
<template>
<div id="app">
<samples v-bind:msg="msg"></samples>
<msg :msg="msg" @update:msg="msg = $event"></msg> // changed this line
</div>
</template>
msg.vue
<template>
<div>
<input type="text" :value="msg" @input="$emit('uddate:msg', $event.target.value)" /> // changed this line
</div>
</template>
Answered By - Loi Nguyen Huynh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.