最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Vue Router. Bind data - Stack Overflow

programmeradmin1浏览0评论

I am developing vue app and now I am on step when I should use vue router. But I have a little problem with data bind into router template.

Please help me.

HTML:

<div id="app">
  <h1>Hello App!</h1>
  <p>
    <router-link to="/foo">Go to Foo</router-link>
    <router-link to="/bar">Go to Bar</router-link>
  </p>
  <router-view></router-view>
</div>

Script:

const Foo = { template: '<div>{{foo}}</div>' }
const Bar = { template: '<div>bar</div>' }


const routes = [
  { path: '/foo', ponent: Foo },
  { path: '/bar', ponent: Bar }
]

const router = new VueRouter({
  routes
})


const app = new Vue({
el: '#app',
  router,
  data: function(){
    return {foo: "asdasdas"}
  }
})

{{foo}} bind doesn't work.

Live example: /

I am developing vue app and now I am on step when I should use vue router. But I have a little problem with data bind into router template.

Please help me.

HTML:

<div id="app">
  <h1>Hello App!</h1>
  <p>
    <router-link to="/foo">Go to Foo</router-link>
    <router-link to="/bar">Go to Bar</router-link>
  </p>
  <router-view></router-view>
</div>

Script:

const Foo = { template: '<div>{{foo}}</div>' }
const Bar = { template: '<div>bar</div>' }


const routes = [
  { path: '/foo', ponent: Foo },
  { path: '/bar', ponent: Bar }
]

const router = new VueRouter({
  routes
})


const app = new Vue({
el: '#app',
  router,
  data: function(){
    return {foo: "asdasdas"}
  }
})

{{foo}} bind doesn't work.

Live example: https://jsfiddle/xgrjzsup/4430/

Share Improve this question asked Dec 6, 2017 at 16:54 snowilsnowil 1011 silver badge8 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

From the guide on ponents :

Every ponent instance has its own isolated scope. This means you cannot (and should not) directly reference parent data in a child ponent’s template. Data can be passed down to child ponents using props.

and Foo is a child ponent of your app set via the router.

One way to pass data from parent to child is to use props.

Modify your Foo definition to accept a foo property:

const Foo = { 
    props: ['foo'],
    template: '<div>{{foo}}</div>' 
}

and bind the parent property in the template

<router-view :foo="foo"></router-view>

An updated Fiddle : https://jsfiddle/xgrjzsup/4431/

in your case there are two ways you can access that "foo" var.

{{$parent.foo}}
{{$root.foo}}

But consider using Vuex for sharing data in your application - https://github./vuejs/vuex Or pass that foo as a parameter to the route -https://router.vuejs/en/essentials/passing-props.html

Ofc it does not work. you have to set the data on the template you use.

in your case:

const Foo = {
  template: '<div>{{foo}}</div>',
  data () {
    return {
      foo: 'magic'
    }
  }
}

Cheers and happy coding.

发布评论

评论列表(0)

  1. 暂无评论