一、父傳子
方式一
父傳子主要通過在父組件v-model綁定數據,在子組件進行用props進行數據的接收
父組件
<template> <div id="container"> <Child :msg="data"></Child> </div> </template> <script> import Child from "@/components/Child"; export default { data() { return { data: "父組件的值" }; }, methods: { }, components: { Child } }; </script>
子組件
<template> <div id="container"> <h1>{{msg}}</h1> </div> </template> <script> export default { data() { return {}; }, props:["msg"] }; </script>
方式二
父組件觸發子組件的方法,主要通過$refs來觸發,同時傳參
父組件
<template> <div id="container"> <h1 @click="getData">點擊將觸發子組件方法,並把參數傳給子組件</h1> <child ref="mychild"></child> </div> </template> <script> import Child from "@/components/Child"; export default { data() { return { name: '', age: '' }; }, components: { Child } methods: { getData(){ //觸發子組件方法,並傳參 this.$refs.mychild.init("chrchr","120"); } }, }; </script>
子組件
<template> <div id="container"> <h1>{{name}}</h1> <h1>{{age}}</h1> </div> </template> <script> export default { props:["msg"], data() { return { name: '', age: '' }; }, mounted:{ }, method:{ //父組件觸發子組件的init方法 init(name,age){ this.name = name; this.age = age; } } }; </script>