Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue Router. Bind data

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', component: Foo },
  { path: '/bar', component: 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.net/xgrjzsup/4430/

like image 591
snowil Avatar asked Dec 06 '17 16:12

snowil


People also ask

Does Vue have data binding?

Vue provides its own set of directives used to dynamically bind our data to the templates. Text Binding: It is used when we need to bind the content of any HTML in Vue. The syntax for using text binding is by using the v-text directive in any HTML element and a data property should be assigned to it.

Is Vue 2 way data binding?

Vue is also perfectly capable of powering sophisticated Single-Page Applications in combination with modern tooling and supporting libraries. The v-model directive makes two-way binding between a form input and app state very easy to implement.

What does binding mean in Vue?

The v-bind directive is a Vuejs directive used to bind one or more attributes, or a component prop to an element. If that attribute is binded to our data defined in Vuejs instance then dynamically changes can be observed as data changes.


1 Answers

From the guide on components :

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

and Foo is a child component 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.net/xgrjzsup/4431/

like image 142
nikoshr Avatar answered Nov 04 '22 08:11

nikoshr