1👍
add props
property to your component and set inside it the msg
property :
<script>
export default {
props:{
msg:{
type:String,
default:"Hello"
}
},
data : function(){
},
mounted() {
console.log('Component mounted.')
}
}
</script>
and
<example-component msg="new Hello"></example-component>
UPDATE
after understanding your use case i recommend to use child component ref
const ExampleComponent = Vue.component('example-component', {
template: `
<div>
<h2>Example component</h2>
<div>{{msg}}</div>
</div>
`,
data() {
return {
msg: "Hello"
}
}
});
window.root = new Vue({
el: '#app',
components: {
ExampleComponent
}
});
root.$refs.example.msg = "new hello"
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<script src="https://unpkg.com/vue@2.5.17/dist/vue.js"></script>
</head>
<body>
<div id="app">
<h2>Parent</h2>
<example-component ref="example"></example-component>
</div>
</body>
</html>
0👍
TL;DR Have a look at this example, it does what you want: https://codesandbox.io/s/88ojwpjq88
You need to distinguish between data
(the components private data) and props
(data passed to the child component). Read this section of the Vue.js guide: https://v2.vuejs.org/v2/guide/components.html
In your component, you’ll need to declare the prop:
export default {
props : ['msg'],
mounted() {
console.log('Component mounted.')
}
}
Then you can bind a data to the child component like this:
<example-component :msg="myMessage"></example-component>
, assuming the parent component has myMessage
declared like this:
data : function(){
return {
myMessage : "Hello"
}
}
To change the value, you can bind it to some sort of input. Here’s an example w/ a text field: <input v-model="myMessage">
.
If you enter sth. into this field, you should see the bound value in your component update.
Do read the manual here: https://v2.vuejs.org/v2/guide/index.html. It’s really good, your questions are covered entirely in there.
0👍
Add the property to your component, make it parent-to-child, that is, you will bind the property within the component, and you can pass data to that property.
Depending on the flow, you must identify how you will do this, whether it is from father to son or from child to father. To pass data to child, you pass through props, if you pass from child to parent, you will use $ emit.
https://v2.vuejs.org/v2/guide/components.html#Passing-Data-to-Child-Components-with-Props
If you use parent to child you will do it the following way.
Pai.vue
<template>
<div> {{msg}} </div>
</template>
<script>
export default {
props: {
msg: {
type: String,
default: 'Hello'
}
}
}
</script>
Ai Inside the child component you call the parameter
<template>
<div>
<parent :msg="valueMsg"/>
</div>
</template>
enter code here
son.vue
<script>
import pai from './pai'
export default {components: {parent},
data: () => ({
valueMsg = 'Hello Test'
})
}