Quantcast
Channel: jun01tの日記
Viewing all articles
Browse latest Browse all 87

Vue.jsのrefsとemit

$
0
0

refs

this.$refsはref="childComponent"をつけた子コンポーネントを親コンポーネントでthis.$refs.childComponent.childMethod();で親コンポーネントから子コンポーネントのメソッドやthis.$refs.childComponent.childData = "";などと親コンポーネントから子コンポーネントのdata属性にアクセスができます。

コンポーネント

data() {
  return {
    childData: "child data";
  }
}
methods: {
  childMethod() {
     alert("call child method!");
  }
}

コンポーネント

<ChildComponent ref="childComoonent" />

methods : {
  callChildMethod() {
    this.$refs.childComponent.childMethod();
  }
  getChildData() {
    const childData =  this.$refs.childComponent.childData;
    console.log(childData);
}

emit

this.$emitは子コンポーネントから親コンポーネントにdataが渡せます。

コンポーネント

<div @click="$emit('click',childData)”>click me!</div>

コンポーネント

<ChildComponent @click="parentData = $event"/>

$eventにchildDataの値が渡ります。


Viewing all articles
Browse latest Browse all 87

Trending Articles