1

I've got a main-component in that main-component I've a sub-component with vue.js 2.0.

The problem is that the sub-component uses the methods in the main-component.

I've made an example:

Vue.component('main-component', {
  template: '<p>This is the main component. <sub-component><button @click="test()">If this button is presses: "sub-component" must show up. </button></sub-component></p>',
  methods: {
  	test() {
    	   alert('main-component');
        }
  }
})

Vue.component('sub-component', {
  template: '<p>This is sub-component <slot></slot> </p>',
  methods: {
       test() {
      	alert('sub-component');
      }
  }
})

var app = new Vue({
  el: '#app'
})
<script src="https://vuejs.org/js/vue.min.js"></script>
<div id="app">
  <main-component></main-component>
</div>

How do I make sure the sub-component uses it's own methods, and in this case give an alert of: 'sub-component' instead of 'main-component' when the button is being pressed?

6
  • vuejs.org/v2/guide/components.html#Compilation-Scope Commented Jun 25, 2017 at 11:24
  • So it's not possible? Commented Jun 25, 2017 at 11:27
  • I do not think so. Commented Jun 25, 2017 at 11:28
  • Looks like it's a good time to introduce vuex Commented Jun 25, 2017 at 11:52
  • You have a couple of answers below. Can we get some feedback on whether either of them worked for you? Commented Jul 5, 2017 at 18:57

2 Answers 2

1

Use a scoped slot.

Vue.component('main-component', {
  template:  `
    <p>This is the main component. 
      <sub-component>
        <template scope="{test}">
          <button @click="test()">If this button is presses: "sub-component" must show up. </button>
        </template>
      </sub-component>
    </p>`,
  methods: {
    test() {
           alert('main-component');
        }
  }
})

Vue.component('sub-component', {
  template: '<p>This is sub-component <slot :test="test"></slot> </p>',
  methods: {
       test() {
        alert('sub-component');
      }
  }
})

var app = new Vue({
  el: '#app'
})
<script src="https://vuejs.org/js/vue.min.js"></script>
<div id="app">
  <main-component></main-component>
</div>

Sign up to request clarification or add additional context in comments.

1 Comment

@Jamie No problem :)
0

Perhaps you can try something like this:

<sub-component ref="sub"><button @click="$refs.sub.test()">...</button></sub-component>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.