Vue TypeError:无法读取未定义的属性“ loggedIn”

时间:2020-06-14 04:37:22

标签: javascript vue.js vuejs2

基于该错误,问题在于吸气剂未检索任何数据。我试图更改商店的导入,因为Quasar将其设置为默认设置,但这样做只会使情况变得更糟,我也尝试调试这些错误数小时。还尝试过更改商店和路由器的默认导出,但没有意义,因为它们也已经从Quasar内置了设置。

Login.vue

<template>
  <div>
    <q-page>
      <h5>Login Page</h5>
      <q-input name="user" v-model="username" filled label="Username" />
      <q-input name="pass" v-model="password" filled label="Password" />
      <q-btn @click="login" label="Login" />
      <li v-if="!loggedIn">
        <router-link to="/register">Register</router-link>
      </li>
    </q-page>
  </div>
</template>

<script>
import { mapMutations } from "vuex";

export default {
  name: "login",
  data() {
    return {
      username: "",
      password: ""
    };
  },
  computed: {
    loggedIn() {
      return this.$store.getters.loggedIn;
    }
  },
  methods: {
    login() {
      this.$store
        .dispatch("LOGIN", {
          username: this.username,
          password: this.password
        })
        .then(response => {
          this.$router.push("/addsub");
        })
        .catch(error => {
          console.log(error);
        });
    }
  }
};
</script>

<style>
</style>

store.js

import Vue from 'vue'
import Vuex from 'vuex'

import { getField, updateField } from 'vuex-map-fields'
import axios from 'axios'

// import example from './module-example'

Vue.use(Vuex)

/*
 * If not building with SSR mode, you can
 * directly export the Store instantiation;
 *
 * The function below can be async too; either use
 * async/await or return a Promise which resolves
 * with the Store instance.
 */

export default function (/* { ssrContext } */) {
  const Store = new Vuex.Store({
    modules: {
      // example
    },
    state: {
      token: localStorage.getItem('access_token') || null,
      subData: {
        subjectName: ''
      },
      testItems: {
        testId: '',
        subjectName: '',
        existingTest: '',
        question: '',
        answer: '',
        studentAnswer: ''
      }
    },
    mutations: {
      sendData: state => {
        const config = {
          headers: { 'Content-Type': 'application/json' }
        }
        axios
          .post(
            'http://localhost/MyComposer/?submitId=0',
            {
              subjectName: state.subData.subjectName
            },
            config
          )
          .then(res => {
            console.log(res)
            alert(res.data)
          })
          .catch(error => {
            console.log(error.response)
          })
      },
      //FOR TEACHER
      submitTestData: state => {
        const config = {
          headers: { 'Content-Type': 'application/json' }
        }
        axios
          .post(
            'http://localhost/MyComposer/?submitId=1',
            {
              subjectName: state.testItems.subjectName,
              question: state.testItems.question,
              answer: state.testItems.answer
            },
            config
          )
          .then(res => {
            console.log(res)
            alert(res.data)
          })
          .catch(error => {
            console.log(error.response)
          })
      },
      //FOR STUDENT
      submitData: state => {
        const config = {
          headers: { 'Content-Type': 'application/json' }
        }
        axios
          .post(
            'http://localhost/MyComposer/?submitId=2',
            {
              existingTest: state.testItems.existingTest,
              studentAnswer: state.testItems.studentAnswer
            },
            config
          )
          .then(res => {
            console.log(res)
            alert(res.data)
          })
          .catch(error => {
            console.log(error.response)
          })
      },
      updateField,
      logMeIn (state, token) {
        state.token = token
      },
      destroyToken (state) {
        state.token = null
      }
    },
    getters: {
      getField,
      loggedIn (state) {
        return state.token != null
      }
    },
    actions: {
      LOGIN (context, payload) {
        return new Promise((resolve, reject) => {
          axios
            .post('http://localhost/MyComposer/?submitId=3', payload)
            .then(response => {
              console.log(payload.username)
              console.log(payload.password)
              console.log(response.data)
              console.log(response.data.username)
              console.log(response.data.password)
              for (var i = 0; i < response.data.length; i++) {
                if (
                  response.data[i].Username === payload.username &&
                  response.data[i].Password === payload.password
                ) {
                  alert('Logged In Successfully!')
                  console.log(payload)
                  console.log(response.data)
                  resolve(response)

                  const token = response.data[i].UserId
                  console.log(token)
                  localStorage.setItem('access_token', token)
                  context.commit('logMeIn', token)
                }
              }
            })
            .catch(error => {
              reject('Incorrect Username or password. Please try again!')
              console.log(error)
            })
        })
      },
      destroyToken (context) {
        axios.defaults.headers.common['Authorization'] =
          'Bearer ' + context.state.token
        if (context.getters.loggedIn) {
          return new Promise((resolve, reject) => {
            axios
              .post('http://localhost/MyComposer/')
              .then(response => {
                for (var i = 0; i < response.data.length; i++) {
                  if (
                    response.data[i].Username === payload.username &&
                    response.data[i].Password === payload.password
                  ) {
                    alert('Logged In Successfully!')
                    console.log(payload)
                    console.log(response.data)
                    resolve(response)

                    console.log(token)
                    localStorage.removeItem('access_token')
                    context.commit('destroyToken')
                  }
                }
              })
              .catch(error => {
                localStorage.removeItem('data')
                context.commit('destroyToken')
                console.log(error)
              })
          })
        }
      }
    },
    // enable strict mode (adds overhead!)
    // for dev mode only
    strict: process.env.DEV
  })

  return Store
}

Router.js

import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes'
// import { store } from '../store/index'
import { store } from 'quasar/wrappers'

Vue.use(VueRouter)

/*
 * If not building with SSR mode, you can
 * directly export the Router instantiation;
 *
 * The function below can be async too; either use
 * async/await or return a Promise which resolves
 * with the Router instance.
 */

export default function (/* { store, ssrContext } */) {
  const router = new VueRouter({
    scrollBehavior: () => ({ x: 0, y: 0 }),
    routes,
    store,
    // Leave these as they are and change in quasar.conf.js instead!
    // quasar.conf.js -> build -> vueRouterMode
    // quasar.conf.js -> build -> publicPath
    mode: process.env.VUE_ROUTER_MODE,
    base: process.env.VUE_ROUTER_BASE
  })

  router.beforeEach((to, from, next) => {
    if (to.matched.some(record => record.meta.requiresAuth)) {
      if (store.getters.loggedIn) {
        next({
          path: '/'
          // query: { redirect: to.fullPath }
        })
      } else {
        next()
      }
    } else if (to.matched.some(record => record.meta.requiresVisitor)) {
      if (store.getters.loggedIn) {
        next({
          path: '/addsub'
          // query: { redirect: to.fullPath }
        })
      } else {
        next()
      }
    } else {
      next() // make sure to always call next()!
    }
  })

  return router
}

routes.js

// import VueRouter from 'vue-router'

// const router = new VueRouter({
const routes = [
  {
    path: '/',
    component: () => import('layouts/MyLayout.vue'),
    children: [
      {
        path: '',
        component: () => import('pages/Index.vue')
      },
      {
        path: '/subjectntestlist',
        component: () => import('pages/SubTestList.vue'),
        meta: {
          requiresAuth: true
        }
      },
      {
        path: '/addsub',
        component: () => import('pages/FormData.vue'),
        meta: {
          requiresAuth: true
        }
      },
      {
        path: '/logout',
        component: () => import('pages/Logout.vue'),
        meta: {
          requiresAuth: true
        }
      },
      {
        path: '/register',
        component: () => import('pages/Register.vue'),
        meta: {
          requiresVisitor: true
        }
      },
      {
        path: '/newtest',
        component: () => import('pages/AddTest.vue'),
        meta: {
          requiresAuth: true
        }
      },
      {
        path: '/testlist',
        component: () => import('pages/TestList.vue'),
        meta: {
          requiresAuth: true
        }
      }
    ]
  }
]
// })

// Always leave this as last one
if (process.env.MODE !== 'ssr') {
  routes.push({
    path: '*',
    component: () => import('pages/Error404.vue')
  })
}

export default routes

1 个答案:

答案 0 :(得分:1)

我终于开始工作了。如果您要在Quasar工作,请取消注释他们为您制作的东西,也就是保留字。我这样做解决了我的问题 而不是仅仅为了调出商店而创建新的Vue组件。另外,您完全不必删除导出默认值,因为它们实际上对简化与其他组件的连接非常有帮助。

<script type="text/javascript">
    $(document).ready(function() {
        $('#province').on('change', function(){
            var select=$(this).val();
            console.log(select);
        });
    });
</script>