简体   繁体   中英

VueJS slots: Why child method passed in via slot from parent doesn't work?

I have a simple vue codesandbox demo .

In this demo, I pass in a method to a child component (defined in child) via slots from parent. However that method does not execute when clicked on button to which this method is attached.

I want to know WHY child methods when passed (from parent) via slots does not work. I'm more interested in the logic behind this.

App.vue

<template>
  <div id="app">
    <img width="25%" src="./assets/logo.png" />
    <user>
      <button @click="changeName('Don')">Change Name</button>
    </user>
  </div>
</template>

<script>
import user from "./components/user";

export default {
  name: "App",
  components: {
    user
  },
  data: function() {
    return {
      msg: "Name is Bond.. James Bond"
    };
  }
};
</script>

User.vue

<template>
  <div class="wrapper">
    <h2>My name is "{{myName}}"</h2>
    <slot></slot>
  </div>
</template>

<script>
export default {

  data() { 
    return {
      myName: 'Bond'
    }
  },

  methods: {
    changeName: function(newName){
      this.myName = newName
    }
  }
};
</script>

Thank You.

If you call the method in the parent, you need to also define the method in the parent. This is regardless of slot or not.

Any methods called in the template refer to that component's instance only. That is the byproduct of not needing a reference to this .

In your example, to give the parent access to myName , use a scoped slot and pass a setter, or child instance, up to the slot parent. Or provide a click method to the slot parent.

This goes hand-in-hand with why events are not emitted to the child. See Emit event from content in slot to parent for more information.

Use props if you want pass a data to children . Use emit if you want pass a data to parent .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM