Vue ref方式父子組件傳值方法

Vue ref方式父子組件傳值方法

<!doctype html>

<html>

<head>

<meta charset="UTF-8">

<script src="https://cdn.bootcss.com/vue/2.3.2/vue.min.js"></script>

</head>

<body>

<div id="box">

<v-tpl1></v-tpl1>

</div>

<template id="tpl1">

<div>

? <p>{{msg1}}</p>

? <!--觸發(fā)拿子組件值的函數(shù)-->

? <button @click="getChild">父拿子的值</button>

? <!--通過ref綁定子組件的值-->

? <v-tpl2 ref="shit"></v-tpl2>

</div>

</template>

<template id="tpl2">

<p>{{msg2}}</p>

</template>

<script>

new Vue({

? el: '#box',

? components: {

? 'v-tpl1': {

? ? template: '#tpl1',

? ? data(){

? ? return {

? ? ? msg1: 'msg1'

? ? }

? ? },

? ? methods: {

? ? //父組件定義一個方法通過refs拿到子組件的值

? ? getChild(){

? ? ? console.log(this.$refs.shit.msg2)

? ? }

? ? },

? ? components: {

? ? 'v-tpl2': {

? ? ? template: '#tpl2',

? ? ? data(){

? ? ? return {

? ? ? ? msg2: 'msg2'

? ? ? }

? ? ? }

? ? }

? ? }

? }

? }

})

</script>

</body>

</html>


子拿父的值

<!doctype html>

<html>

<head>

<meta charset="UTF-8">

<script src="https://cdn.bootcss.com/vue/2.3.2/vue.min.js"></script>

</head>

<body>

<div id="box">

<v-tpl1></v-tpl1>

</div>

<template id="tpl1">

<div>

? ? <v-tpl2></v-tpl2>

</div>

</template>

<template id="tpl2">

<div>

? <button @click="getParent">子拿父的值</button>

? <p>{{msg2}}</p>

</div>

</template>

<script>

? ? new Vue({

? el: '#box',

? components: {

? 'v-tpl1': {

? ? template: '#tpl1',

? ? ? ? data(){

? ? return {

? ? ? msg1: 'msg1'

? ? }

? ? },

? ? components: {

? ? ? ? 'v-tpl2': {

? ? ? ? template: '#tpl2',

? ? ? data(){

? ? ? return {

? ? ? ? msg2: 'msg2'

? ? ? }

? ? ? },

? ? ? methods:{

? ? ? getParent(){

? ? ? ? ? console.log(this.$parent.msg1)

? ? ? }

? ? ? }

? ? }

? ? }

? }

? }

})

</script>

</body>

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 組件簡介 組件系統(tǒng)是Vue.js其中一個重要的概念,它提供了一種抽象,讓我們可以使用獨(dú)立可復(fù)用的小組件來構(gòu)建大型應(yīng)...
    前端一菜鳥閱讀 936評論 0 16
  • Vue 實(shí)例 屬性和方法 每個 Vue 實(shí)例都會代理其 data 對象里所有的屬性:var data = { a:...
    云之外閱讀 2,361評論 0 6
  • 第一章 Vue概述 what? Vue是實(shí)現(xiàn)UI層的漸進(jìn)式j(luò)s框架,核心庫關(guān)注視圖層,簡單的ui構(gòu)建,復(fù)雜的路由控...
    fastwe閱讀 832評論 0 0
  • 一、追問"為什么"來反思自己所追求的東西。 a 為什么我要追求苗條的身材? 因?yàn)槲矣X得瘦可以提高顏值和增加氣質(zhì)(外...
    吾時又六分之七閱讀 616評論 0 2
  • 昨天因?yàn)樘В瑳]有寫簡書,只字未寫。 昨天婆婆回來了,孩子歡呼雀躍,嘰嘰喳喳的,看的出來非常高興,孩子從小和爺爺奶...
    一心飛揚(yáng)閱讀 234評論 0 0

友情鏈接更多精彩內(nèi)容