首页 > 解决方案 > laravel vue 插件使用方法

问题描述

我正在尝试 laravel vue 应用程序中的 vue cook 插件,这就是我的做法

<template>
    <div class="tranbg" v-if="first">
        <div>hello</div>
        <button @click="turnOff">ok</button>        
    </div>
</template>

<script>


export default {
    data(){
        return {
            first: true
        }
    },
    computed(){
        if (this.$cookie.get('firstvisit') == 'visited') {
            this.first = false
        }
    },
    methods:{

        turnOff(){
            this.first = false
            this.$cookie.set('firstvisit', 'visited', 30000); // 30,000 days
        }
    }   
}
</script>

我的 app.js

import VueCookies from '../../../node_modules/vue-cookies'
Vue.use(VueCookies)

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

收到错误 app.js?v=226:103199 Uncaught TypeError: Cannot read property 'set' of undefined 当我单击按钮时

标签: laravelvue.js

解决方案


Vue.js文档告诉您在初始化 Vue 实例之前注册插件。

在您的应用程序的某个时刻,您会创建一个new Vue(...)实例。您需要在Vue.use(VueCookies)此之前调用,而不是在组件的文件中调用。由于在导入组件时 Vue 可能已经实例化,因此$cookie尚未设置属性。


推荐阅读