vue.js를 사용하여 앱의 다른 구성 요소에서 구성 요소 이벤트를 트리거하는 방법은 무엇입니까?

RichC

사이트의 모든 페이지에서 실행될 구성 요소 (카운트 다운 타이머)가 있습니다. 최상위 App.vue 파일에서 참조됩니다. 계층 체인의 깊이에 관계없이 앱 내부의 다른 구성 요소에서 해당 구성 요소 내부의 이벤트를 호출 할 수 있어야합니다 (시간을 다시 시작하기 위해) (즉, 모든 이벤트를 실행하고 $ emits를 실행하고 싶지 않습니다. 이 하나에 대한 사이트의 단일 구성 요소).

서버에 ajax 호출을 할 때마다 타이머를 재설정하고 싶습니다. 따라서 아래 코드에서 버튼을 클릭 할 때마다 startCountdown(true)카운트 다운 타이머 구성 요소 에서 이벤트 를 트리거하고 싶습니다 .

다음은 내가하는 일에 대한 codesandbox 예제입니다.

Main.js

import Vue from "vue";
import App from "./App.vue";
import Vuex from "vuex";
import router from "./router/router";
import VueAwesomeCountdown from "vue-awesome-countdown";

Vue.config.productionTip = false;

Vue.use(Vuex);
Vue.use(VueAwesomeCountdown);

const store = new Vuex.Store({
  state: {
    count: 0
  },
  getters: {
    count: state => {
      return state.count;
    }
  },
  mutations: {
    increment: state => state.count++,
    decrement: state => state.count--
  },
  actions: {
    increment: context => {
      context.commit("increment");
    },
    decrement: context => {
      context.commit("decrement");
    }
  }
});

new Vue({
  el: "#app",
  router,
  store,
  template: "<App />",
  components: {
    App
  }
});

앱보기

<template>
  <div id="app">
    <router-link to="/" class="btn bt-link">Page 1</router-link>&nbsp;|
    <router-link to="/Page2" class="btn bt-link">Page 2</router-link>&nbsp;|
    <router-link to="/Page3" class="btn bt-link">Page 3</router-link>
    <hr>
    <br>
    <br>
    <router-view></router-view>
    <br>
    <br>

    <hr>
    <!-- Timer countdown -->
    <countdown ref="sessionTimer" :left-time="99000">
      <span slot="process" slot-scope="{ timeObj }">Session Timer Countdown: {{ timeObj.ceil.s }}</span>
      <span slot="finish">TIMED OUT!</span>
    </countdown>
    <button class="ml-3 btn btn-warning" @click="restart">Manual Restart</button>
    <hr>
    <!-- The below is just show vuex is wired up correctly -->
    <p>This is just to show that Vuex is working properly.</p>
    <p>{{ count }}</p>
    <p>
      <button @click="increment">+</button>
      <button @click="decrement">-</button>
    </p>
  </div>
</template>

<script>
export default {
  name: "App",
  computed: {
    count() {
      return this.$store.getters.count;
    }
  },
  methods: {
    restart() {
      this.$refs.sessionTimer.startCountdown(true);
    },
    increment() {
      this.$store.dispatch("increment");
    },
    decrement() {
      this.$store.dispatch("decrement");
    }
  },
  components: {}
};
</script>

<style>
#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 20px;
}
</style>

Page2.view

<template>
  <div>
    <h1>Page 2</h1>
    <br>
    <br>
    <button class="btn btn-success" @click="interactWithServer">Interact with Server 2</button>
    <br>
    <br>
    <SubComponent></SubComponent>
  </div>
</template>

<script>
import SubComponent from "./Page2-SubComponent.vue";

export default {
  methods: {
    interactWithServer() {
      //This function will interact with server but I need to start countdown timer over again first
      //axios call goes here after timer is reset
    }
  },
  components: {
    SubComponent
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style>
</style>

Page-SubComponent.vue

<template>
  <div>
    <h3>SUB COMPONENT</h3>
    <br>
    <br>
    <button class="btn btn-primary" @click="interactWithServer">Interact with Server 2.1</button>
  </div>
</template>

<script>
export default {
  methods: {
    interactWithServer() {
      //This function will interact with server but I need to start countdown timer over again first
      //axios call goes here after timer is reset
    }
  }
};
</script>
압델 릴라 아이 사니

더 짧은 방법이 있는지 확실하지 않지만 저장소에서 변수를 트리거 한 다음 App.vue파일 에서 해당 변수를 듣고 실행 restart하여 .. 여기에 codesandbox 샘플이 있습니다.

// store

state: {
  changed: false
}

getters: {
  changed: (state) => state.changed
}

mutation: {
  changed: (state) => state.changed = !state.changed
}
// App.vue

 computed: {
    trigger() {
      return this.$store.getters.changed
    }
  },
  methods: {
    restart() {
      this.$refs.sessionTimer.startCountdown(true);
    }
  },
  watch: {
    trigger() {
      this.restart()
    }
  }

다른 구성 요소에서 :

interactWithServer() {
  this.$store.commit("changed");
}

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관