1
votes

I am very new to Vue and I am having difficulty accessing data in main Vue instance from component. In the Vue instance I have:

var vm = new Vue({
    computed: {},
    data: {
      show: true
    },

and in the component, I want to do something like:

<button v-show="vm.show" @click="setDefaults(styleguide)">Set Default</button>

My goal is when 'show' value changes, I want to display/hide the button. It is little difficult/weird because I create template in the component, not in the html. When I try this code, it doesn't understand 'vm.show'. I feel like I need to create data in the component and tie the data to the 'show' variable, or create computed in the component or something (I believe computed is like watcher?). If there is easy way to handle this, please help.

3
Please share your full code in jsfiddle or any other online code editor. ThanksNazmul Hossain

3 Answers

2
votes

I'm also new to VueJs, but I believe the issue is you haven't provided the el argument to the Vue instance, and in this case assigning the Vue instance to a variable doesn't do anything.

I think you want something like

<div id="app">
  <button v-show="show" @click="setDefaults(styleguide)">Set Default</button>
</div>

<script>
new Vue({
  el: '#app',
  computed: {},
  data: {
    show: true
  },
  ...
);
</script>
0
votes

Two things, in the template all variables are already scoped from the component so you don't need the vm. in there. The second thing is that the data property of a component expects a function which returns an object.

var vm = new Vue({
  computed: {},
  data: () => ({
    show: true
  }),

<button v-show="show" @click="setDefaults(styleguide)">Set Default</button>

If you need to access data from a parent component you will need to pass it on using props. you can also try to do it using provide/inject if that suits your usecase better

0
votes

So I guess my question wasn't very clear, but I got it to figure it out. In the component code, I needed to add:

Vue.component('styleguide', {
    computed: {
        show: function () {
            return vm.show
        }
    },
    props: ['styleguide'],
    template: `
    <div>
        <div>
            <p>
                <button v-show="show" @click="setDefaults(styleguide)">Set Default</button>

This allows me to access 'show' in the main Vue instance from the component template. Whenever other component modifies 'show' variable in the main Vue instance, the button disappears/reappears. I am not sure if this makes sense, but this is how I got it to work.