Vue.js插件错误:未定义

时间:2017-10-24 13:04:53

标签: vue.js

我正在尝试使用GodofBrowser中的插件,如上所述,但我收到错误

  this.$dialog.confirm('Please confirm to continue')
  Uncaught TypeError: Cannot read property 'confirm' of undefined

所以这个。$ plugin是未定义的....为什么?

// I installed it via npm 
npm install vuejs-dialog

main.js

// I imported it
import Vue from "vue"
import VuejsDialog from "vuejs-dialog"

// and I told Vue to install it 
Vue.use(VuejsDialog)

然后我尝试在我的App.vue中使用'click'方法:

App.vue

    <template>
      <div id="app" class="container">
        <ul class="navigation">
          <li id="home"><router-link :to="{ name: 'Home' }" >Home</router-link></li>
          <li id="shoppinglists" v-if="!logged">
            <span @click.capture="clicked">
              <router-link :to="{ name: 'ShoppingLists' }" >Shopping Lists</router-link>
            </span>
          </li>
          <li v-else id="shoppinglists"><router-link :to="{ name: 'ShoppingLists', params: { id: currentUserId } }" >Shopping Lists</router-link></li>
        </ul>
        <router-view></router-view>
      </div>
    </template>

    <script>
    import store from '@/vuex/store'
    import { mapGetters } from 'vuex'

    export default {
      name: 'app',
      methods: {
        clicked: (event) => {
          event.preventDefault()
          console.log('clicked!'). // got it in console
          this.$dialog.confirm('Please confirm to continue') // !ERROR
          .then(function () {
            console.log('Clicked on proceed')
          })
          .catch(function () {
            console.log('Clicked on cancel')
          })
        }
      },
      computed: {
        ...mapGetters({ currentUserId: 'getCurrentUserId', logged: 'getLogged' })
      },
      store
    }
    </script>

2 个答案:

答案 0 :(得分:2)

应该使用:Vue.prototype,而不是这个!

Vue.prototype.$dialog.confirm('Please confirm to continue')

答案 1 :(得分:1)

这是Vue应用程序常见的绊脚石 - 您可以在official Vue documentation中找到以下内容:

  

不要在选项属性或回调上使用箭头功能,例如   created :()=&gt; console.log(this.a)或vm。$ watch(&#39; a&#39;,newValue =&gt;   this.myMethod())。

     

由于箭头功能绑定到父级   上下文,这通常不会像你期望的那样成为Vue实例   导致Uncaught TypeError等错误:无法读取属性   未定义或未捕获的TypeError:this.myMethod不是函数。

尝试使用普通功能:

methods: {
    clicked: function (event) {
      event.preventDefault()
      console.log('clicked!'). // got it in console
      this.$dialog.confirm('Please confirm to continue') // !ERROR
      .then(function () {
        console.log('Clicked on proceed')
      })
      .catch(function () {
        console.log('Clicked on cancel')
      })
    }
  }