VueJS:在路由器之间传递数据

时间:2020-03-30 20:51:05

标签: javascript vue.js

我尝试了无数次使用道具在视图之间传递数据,但似乎无法使其正常工作。想法是将数据从一条路径传递到另一条路径,最后显示所有用户输入的数据。

组件A

<script>
export default {
  name: 'DependencyStatus',
  data: function () {
    return {
      efcForm: {
        born: false
      }
    }
  },
  methods: {
    processForm: function () {
      this.$router.push({name: 'student', props: {messaged: 1}})
      console.log({born: this.efcForm.born,})
    }
  }
}
</script>

组件B

<script>

export default {
  name: 'StudentData',
  props: ['messaged'],
  data: function () {
      return {
          born: this.$route.messaged
      }
  },
  methods: {
      checkForm: function() {
          console.log({checkForm: this.born })
      }
  }
  
}
</script>

我的路线:

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
  },
  {
    path: '/student',
    name: 'student',
    component: Student,
    props: true
  },

1 个答案:

答案 0 :(得分:0)

您可以使用dynamic param从一条路线传递数据 组成另一个。

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
  },
  {
    path: '/student/:messaged', // <-- [1] Add dynamic param
    name: 'student',
    component: Student,
    props: true
  }
]

组件A:

methods: {
 processForm: function () {
  this.$router.push({name: 'student', params: { messaged: 1 } }) // <-- [2] pass `messaged` as param instead of prop
 }
}

组件B:

methods: {
 checkForm: function() {
  console.log({ messaged: this.$route.params.messaged }) // <-- [3] excess in the other component via route param
 }
}

PS:如果传递复杂的ds,请考虑使用Vuex

相关问题