【问题标题】:Vue.js - how to pass data to another route?Vue.js - 如何将数据传递到另一条路线?
【发布时间】:2017-10-09 14:12:31
【问题描述】:

我是 Vue.js 的新手,有一个问题。

首先我有这段代码来从我的后端应用程序中获取所有数据:

var app2 = new Vue({
    delimiters: ['%%', '%%'],
    el: '#app2',

    data: {
        articles: []
    },

    mounted : function()
    {
        this.loadData();
    },

    methods: {
        loadData: function() {
            this.$http.get('/backend/FpArticle/articleApi').then(response => {
                // get body data
                this.articles = response.body;
            }, response => {
                // error callback
            });
        },

    },

我想这很简单。现在我在表格视图的前端显示文章中的数据。所以我做了这样的事情:

<tr v-for="article in articles">
  <td>{{ article.name }}</td>
</tr>

这行得通。但现在我想创建一个编辑掩码,用户可以在其中更改本文的一些数据元素。所以我假设做这样的事情:

<tr v-for="article in articles">
  <td>{{ article.name }}</td>
  <td><a href="/article/{{ article.id }}">edit</a></td>
</tr>

所以我需要另一个组件来获取 id、读取文章的数据、将其显示在表单中并处理保存事件。我想我知道如何解决后一部分,但是如何使用新组件进行路由?或者有没有在 Vue 中推荐的更好的方法?大概是这样的吧?

<tr v-for="article in articles">
  <td>{{ article.name }}</td>
  <td><button v-on:click="editArticle(article.id)">edit</button></td>
</tr>

我很感激任何提示!谢谢!

【问题讨论】:

  • editArticle,你尝试使用router.push吗?

标签: javascript vue.js vuejs2


【解决方案1】:

是的,你在正确的轨道上。您想使用VueRouter。您必须使用组件配置路由。例如:

const router = new VueRouter({
  routes: [
    { path: '/articles', component: ArticlesList },
    { path: '/articles/:id', component: Article }
  ]
})

然后,您将使用&lt;router-link&gt; 访问您的Article 视图(默认情况下将呈现为&lt;a&gt; 标签):

<td><router-link to="'/article/' + article.id">edit</router-link></td>

另外,您需要&lt;router-view&gt;&lt;/router-view&gt; 标签来呈现您的组件视图。路由匹配的组件会在这里渲染。

一切都在文档中 ;-) https://router.vuejs.org/en/essentials/getting-started.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-20
    • 2019-09-22
    • 2016-04-22
    • 2020-11-26
    • 2020-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-24
    相关资源
    最近更新 更多