Vue.js - access data property from within template without using props in vue file

安稳与你 提交于 2019-12-24 06:17:10

问题


In my Laravel + Vue.js SPA (Single Page Application), I am using BootstrapVue and VeeValidate.

In EditProfile.vue file, I want to access the data property namely default_country_code from an attribute in the template namely default_country_code.

I can achieve it by using props i.e: having a data attribute in Vue root instance and then using it in the template with the help of props in EditProfile.vue file.

But I want to use it in the template without using any props. Because if I use props, all the props that I need to use in template sections in different pages have to be defined in Vue root instance . And when those data attributes that will be used as props come from database, I have to make multiple queries in DB in the corresponding Laravel controller method and use them in Vue root instance. And this approach does not seem to be any loosely coupled architecture to me.

In EditProfile.vue page, I have :


    <template>     
             <ValidationProvider vid="name" rules="required" name="name" v-slot="{ valid, errors }">

                  <b-form-group
                                    label="Name:"
                                    label-for="exampleInput1"

                            >


                      <b-form-input

                                v-model="name"
                                default-country-code="default_country_code"
                                :state="errors[0] ? false : (valid ? true : null)" 
                                placeholder="Enter Name"

                       ></b-form-input

                                <b-form-invalid-feedback id="inputLiveFeedback">{{ errors[0] }}</b-form-invalid-feedback>

                  </b-form-group>

             </ValidationProvider>

</template>         


        export default {
                name: "EditProfile",
                props: {

                },
               data: () => ({
                    name:"Mr. XYZ",
                    default_country_code:"FR"

                })

        };

How can I use default_country_code in template attribute without using any props by taking help of the Vue root instance as I said before ?


回答1:


Assuming you're trying to access the value from a child component, you can access Vue's state. For example let someVar = $parent.default_country_code.

That said, using props or something like vuex to store global state, would be better practice.



来源:https://stackoverflow.com/questions/59458265/vue-js-access-data-property-from-within-template-without-using-props-in-vue-fi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!