子傳父
vue子傳父使用$emit傳值
子組件:
<template> <div> <button @click="toParent">點擊傳到父級</button> </div> </template> <script> export default { name: 'child', methods: { toParent () { this.$emit('fromChild', 'child') } } } </script>
父組件
<template> <div> <p>子級傳過來的值:{{childVal}}</p> <child @fromChild="getChild"></child> </div> </template> <script> import child from "@/components/child"; export default { name: 'parent', data () { return { childVal: '' } }, components: { child }, methods: { getChild (v) { this.childVal = v; } } } </script>
頁面未點擊前
點擊后
傳過來啦
父傳子
子組件使用props接收 接收時還可以設置默認值 當沒獲取到值時 會使用設置的默認值
父組件
<template> <div> <child :tochild="parentVal"></child> </div> </template> <script> import child from "@/components/child"; export default { name: 'parent', data () { return { parentVal: 'parent', } }, components: { child } } </script>
子組件
<template> <div> <p>父級傳過來的值:{{tochild}}</p> </div> </template> <script> export default { name: 'child', props: { tochild: String } } </script>
效果
父級定義的值 顯示到子組件的里面啦 有沒有很神奇 有沒有想要試一試