我想更新我的组件中的数据 Vue公司 </跨度> 实例。找到关于如何做相反事情的大量例子,但没有任何内容。
说我有:
Vue.component(‘component’,{道具: { 道具……:{ 默认值:null }},模板:‘#template’,data:function(){ 返回{ 开:假 };}});
现在我想从我的开放到真实 Vue公司 </跨度> 例如:
var root = new Vue公司 </跨度> …
你应该可以用一个 儿童组件参考 。
<script type="text/x-template" id="template" ref="component"> <div>Hello, {{ name }}!</div> </script>
var root = new Vue({ el: '#root', data: {}, methods: { updateComponentData: function() { this.$refs.component.open = true } } });
的 工作实例 强>
const Child = Vue.component('child', { template: ` <div> <h2>Component1</h2> <div>Hello, {{ title }}! <strong>{{ open }}<strong></div> </div> `, data() { return { title: 'component', open: false } } }); var root = new Vue({ el: '#app', components: { Child }, methods: { updateComponentData: function() { //console.log('updateComponentData', this.$refs) this.$refs.component1.open = true } } });
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script> <div id="app"> <h2>Parent</h2> <button v-on:click="updateComponentData">Click me true</button> <child ref="component1"></child> </div>
我刚刚玩了你的代码,下面的代码完美无缺,请尝试一下。我用过Vue'ref'。加 ref 组件中的属性,然后您可以从父级访问该特定组件数据。
ref
Vue.component('component', { props: { prop: { default: null } }, template: '#template', data: () => ({ open: false }) }); var root = new Vue({ el: '#root', data: () => ({}), methods: { updateComponentData: function() { this.$refs.myComponent.open = true } }, });
<script src="https://unpkg.com/vue"></script> <div id="root"> <button @click="updateComponentData">Change</button> <hr> <component ref='myComponent'></component> </div> <script type="text/x-template" id="template" ref="component"> <div>Open: {{ open }}!</div> </script>