vue-router访问组件数据

时间:2017-09-18 09:51:16

标签: javascript vue-router

我正在玩一个从vue-router文档中提供的示例

HTML:

<div id="app">
  <h3>{{title}}</h3>
  <router-link to="/">/home</router-link>
  <router-link to="/foo">/foo</router-link>
  <router-view></router-view>
</div>

JavaScript的:

const Foo = { template: '<div>foo</div>', data: {title: "Foo" }
const Bar = { template: '<div>bar</div>', data: {title: "Bar" }

是否可以在锚点之外访问所选组件数据并更新{{title}}标题?

完整示例是here

1 个答案:

答案 0 :(得分:1)

我有两种可能性。首先是使用this.$parent.title直接编辑父数据。 第二种方法是触发事件this.$parent.$emit('changeTitle', 'foo');

我认为最后一个更好,因为你的状态的控制总是在你的父组件中。

const Home = { 
  template: '<div>Home</div>', 
  data: {
    title: "Home"
  },
  mounted() {
    this.$parent.title = 'home'; // directly
  }
}
const Foo = { 
  template: '<div>Foo</div>', 
  data: {
    title: "Foo"
  },
  mounted() {
    this.$parent.$emit('changeTitle', 'foo'); // emit an event
  }
}

const router = new VueRouter({
  mode: 'history',
  routes: [
    { 
      path: '/', 
      component: Home 
    },
    { 
      path: '/foo', 
      component: Foo 
    }
  ]
})

new Vue({
  router,
  el: '#app',
  data: {
    title: 'Initial'
  },
  destroy() {
    this.$off('changeTitle');
  },
  created() {
    const _self = this;
    
    this.$on('changeTitle', function(newTitle) {
      _self.title = newTitle;
    });
  }
})
<script src="https://npmcdn.com/vue/dist/vue.js"></script>
<script src="https://npmcdn.com/vue-router/dist/vue-router.js"></script>

<div id="app">
  <h3>{{title}}</h3>
  <router-link to="/">/home</router-link>
  <router-link to="/foo">/foo</router-link>
  <router-view></router-view>
</div>