簡體   English   中英

Vue.js 訪問組件方法還是父方法?

[英]Vue.js access component method or parent method?

我是 Vue 的新手,並設法制作了我的第一個應用程序,但出現了一些故障,但到目前為止我真的很喜歡它。 我使用了一個視頻教程,該教程從創建 vue-cli 項目開始,結果由於 webpack 而略有不同。

我已經創建了這個項目,該項目現在主要做它應該做的事情我正在嘗試做一些重構,包括干掉代碼。

在每個頁面上,我都想訪問存儲在 cookie 文件中的變量,我已經在腳本部分的 HomeComponent 上完成了保存和讀取操作,該腳本部分按承諾工作。

<script>
import MenuComponent from '@/components/MenuComponent.vue'
import Typewriter from '@/components/vue-type-writer.vue'

export default {
  name: 'HomeComponent',
  components: {
    MenuComponent,
    Typewriter
  },
  prop:{
      isPlaying: Boolean,
      username: String,
      currentSound: Object
  },
  data() {
      return{
         currentSound: null,
         isPlaying: false,
         username: ''
      }
  },
  methods:{
   clickButton() {
      this.msg= 'test 2'
   },
   toggleSound(){
      var a = this.currentSound;

      if (a.paused) {
        a.play();
        this.isPlaying = true;
      } else {
        a.pause();
        this.isPlaying = false;
      }
   },
   getCookieInfo(){
      var value = "; " + document.cookie;
      var parts = value.split("; weegreename=");
      if (parts.length == 2)
         this.username = parts.pop().split(";").shift();
      else this.username = '';
   },
   seveFormValues (submitEvent) {
      this.username = submitEvent.target.elements.name.value;
      this.$refs.audio1.pause();
      this.$refs.audio2.play();

      var expires = "";
      var days = 31;
      if (days) {
         var date = new Date();
         date.setTime(date.getTime() + (days*24*60*60*1000));
         expires = "; expires=" + date.toUTCString();
      }
      document.cookie = "weegreename=" + (this.username || "")  + expires + "; path=/";

    }
  },
   mounted(){
      this.isPlaying = true;
      this.getCookieInfo();
      if (this.username) this.currentSound = this.$refs.audio2;
      else this.currentSound = this.$refs.audio1;
      this.currentSound.play();
   }
}
</script>

現在,在每個子頁面上,我都想訪問getCookieInfo()方法來檢查用戶名是否已設置。

我試圖在 main.js 的主 App.vue 腳本部分添加它

new Vue({
  router,
  render: h => h(App),
  methods: {
    //here the getCookieInfo code from above
  }
}).$mount('#app')

使用方法創建了一個新組件,然后嘗試通過 componentname.method 在主應用程序中訪問它們,如下所示。

import CookieComponent from '@/components/CookieComponent.vue'

export default {
   // prop:{
   //    isToggled: Boolean
   // },
     components: {
       MenuComponent,
       CookieComponent
     },
   data() {
      return{
         isToggled: false
      }
   },
   methods:{
      clickToggle() {
         this.isToggled = !this.isToggled;
      },

   },
   mounted(){
      CookieComponent.getCookieInfo();
   }
}

我現在不知道最好的方法,將來我會學到更多,但是這個項目對時間很敏感——我決定通過為我的客戶制作一個簡單的網站來學習 vue :)

如果您在每個頁面上都需要它,可以將其放入您的 App.vue。 從那里你有三個選擇:

  1. 將數據作為道具傳遞給子組件。
  2. 創建一個事件總線並將數據發送到需要它的任何組件。
  3. 使用 Vuex 存儲數據並從您的組件中訪問它。

如果您真的想將 cookie 數據保留在組件中,則需要將其發送到組件鏈中。

https://v2.vuejs.org/v2/guide/components.html#Emitting-a-Value-With-an-Event

根據你的鏈有多深以及你有多少兄弟組件,這可能會變得非常混亂,在這些情況下,Vuex 或事件總線可能是一個更好的主意。

不要嘗試做以下事情:

CookieComponent.getCookieInfo();

請查看文檔以查看有關如何進行組件通信的良好示例。

對於那種東西,最好的做法是使用state 它將保存您的應用程序的數據,並允許您跨所有組件/頁面訪問它們。

可以在 Vue 文檔中看到一個簡單的狀態管理,或者直接使用 Vue 官方的狀態管理庫VueX

總結一下它是如何工作的(使用 VueX):

  • 您創建一個 cookieStore:
// Where data will be saved
const state = { cookie: {} }

// Getters allow you to access data
const getters = { cookie: state => state.cookie }

// Mutations allow you to modify the state
const mutations = {
  // Set cookie data
  saveCookie (state, cookieData) {
    state.cookie = cookieData
  }
}
  • 在您的 HomeComponent 中,您將獲取 cookie 信息,並將其保存在存儲中: this.$store.commit('saveCookie', cookieData)
  • 在所有其他組件中,您無需從 cookie 中獲取 cookie 信息,而是可以從存儲中訪問保存的數據並使用它做您想做的事情: this.$store.getters.cookie

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM