将json对象的一个​​组件传递给另一个vue.js [英] Pass json object one component to another vuejs

查看:51
本文介绍了将json对象的一个​​组件传递给另一个vue.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是vuejs的新手,我想将JSON对象传递给同一vue实例中的另一个组件.下面显示我的代码.从组件添加用户到组件查看用户.我尝试了Vue道具,但是没有用非常感谢你.

I'm new to vuejs I want to pass an JSON object to another component within same vue instance. following show the my code. from component add-user to component view-user. I tried vue props but it didn't work Thank you very much.

Vue.component('view-users',{
  props:['user'],
  template: '<span>{{ user.name }}</span>'
}); 

Vue.component('add-user',{
	data: function(){
  		return 	{
      		user:{
          	name:'jhon',
            age:'29',
          }
      }
  }
});

var app = new Vue({
	el:'#app',
 
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>

<div id="app">
<add-user></add-user>

<view-users></view-users>
</div>

推荐答案

道具主要用于将数据从父组件传递到子组件,并且子组件无法直接修改传递的数据并反映父组件上的更改.为了在每个组件周围传递数据,一种很好的方法是使用 Vuex .

Props are mostly for passing data from parent components to child components, and a child component cannot directly modify the passed data and reflect the changes on parent components. In order to pass data around every component, a good way to do it is using Vuex.

首先创建状态,可能类似于

First you create the state, possibly like

const state = {
  user:{
    name:'john',
    age:'29',
  }
}

在最简单的情况下,您暂时不执行任何异步操作,请通过 mutations 修改状态:

And for the simplest case, that you are not doing anything asynchronous for now, you modify the state through mutations:

const mutations = {
  CHANGE_NAME(state, payload) {
    state.user.name = payload
  },
  CHANGE_AGE(state, payload) {
    state.user.age = payload
  }
}

所有这些就绪后,您可以创建Vue商店:

With all these in place you can create the Vue store:

const store = new Vuex.Store({
  state,
  mutations
})

然后在您的Vue实例中使用它:

Then use it in your Vue instance:

const app = new Vue({
  el: '...',
  data: { ... },
  store,
  // ...
})

最后,您可以在组件中按如下方式访问和修改状态:

Finally, in your components, you can access and modify the state as follows:

Vue.component('my-component', {
  data() {
    return {
      // ...
    }
  },
  computed() {
    user() {
      // this is one way to do, you can also check out mapstate
      return this.$store.state.user
    }
  },
  methods: {
    // you can also check out mapMutations
    changeName(val) { this.$store.dispatch('CHANGE_NAME', val) },
    changeAge(val) { this.$store.dispatch('CHANGE_AGE', val) },
  }
})

这是一个简单的示例: http://jsfiddle.net/teepluss/zfab6tzp/6/

Here's a simple example: http://jsfiddle.net/teepluss/zfab6tzp/6/

如果您的应用程序不太大,也可以使用EventBus(教程文档).对于 Vuex ,您可以查看如何使用状态突变此处.

You can also use EventBus if you app is not too big (tutorial and documentation). And for Vuex, you can check out how to use state and mutations here.

这篇关于将json对象的一个​​组件传递给另一个vue.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆