【问题标题】:VueJS multiple components in one viewVueJS 多个组件在一个视图中
【发布时间】:2018-07-23 23:59:27
【问题描述】:

我正在尝试学习 VueJS,它进展顺利,但我遇到了一个问题,我无法让多个组件在一个页面上工作,由于某种原因,html 会加载,但我的 export default 中的所有内容都不起作用.

所以我有 2 个组件:一个 ShortenerComponent 和一个 StatsComponent ShortenerComponent 可以正常工作并完成它应该做的所有事情,但 StatsComponent 只会加载 html 而不会在 export default 内做任何事情@这是我的代码:

StatsComponent.vue(除了方法和html之外,ShortenerComponent是一样的。):

<script>
// get the csrf token from the meta
var csrf_token = $('meta[name="csrf-token"]').attr('content');

export default {
    data() {
        return {

        };
    },

    test() {
        this.getStats();
    },
    methods: {
        // get all the existing urls
        getStats() {
            console.log('console log something');
            axios.get('urls').then((response) => {
                console.log('console log something');
            });
        },

    }
}

我的缩短组件:

<script>
// get the csrf token from the meta
var csrf_token = $('meta[name="csrf-token"]').attr('content');

export default {
    data() {
        return {
            shortUrl: '',
            url: '',
            error: '',
        };
    },

    methods: {
        createUrl() {
            axios({
                method: 'post',
                url: '/',
                data: {
                    _token: csrf_token,
                    url: this.url
                },
            }).then(response => {
                console.log(response);
                this.shortUrl = response.data.hash;
            }).catch(error => {
                this.error = error.response.data.message;
            });
        }
    }
}

最后但并非最不重要的是我的 app.js 文件

Vue.component('shortener',require('./components/ShortenerComponent.vue'));
Vue.component('stats', require('./components/StatsComponent.vue'));

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

我希望有人能弄清楚我做错了什么:D

【问题讨论】:

  • 你能在控制台显示什么错误吗?
  • 控制台未显示错误
  • 你在使用 webpack 吗?还要确保在 webpack 中正确设置了 vue-loader。
  • 您的组件中没有数据、没有挂载、没有创建的属性。您希望展示什么?
  • 什么是test?应该在methods 中吗?

标签: javascript html laravel vue.js


【解决方案1】:

所以在我的代码中我有test 方法,我认为它会调用getStats 方法。我现在没有的是,Vue 有 created 方法,用于在创建实例后运行代码。

所以我要做的是:

function created()
{
   this.getStats();
}

来源:Vue instance Lifecycle Hooks

【讨论】:

  • 考虑到作者本人是发表评论的人,它确实为问题提供了 LQ 答案
猜你喜欢
  • 2022-06-10
  • 2017-08-26
  • 2016-06-04
  • 1970-01-01
  • 2023-01-13
  • 1970-01-01
  • 1970-01-01
  • 2017-07-05
  • 2020-07-23
相关资源
最近更新 更多