简体   繁体   English

Vue JS:从不同组件访问数据

[英]Vue JS: Accessing data from different component

I have a Vue component that has a 'vue-webcam' component inside, my problem is how can I access the "stream" inside of it data and set it to stop using my method out side of that 'vue-webcam' component. 我有一个Vue组件,内部有一个“ vue-webcam”组件,我的问题是如何访问其中的“流”数据并将其设置为停止使用该“ vue-webcam”组件之外的方法。 Is there anyway of or I have to make a state 无论如何还是我必须做出一个陈述

<script>
  export default{
    components:{
      'vue-webcam':{
        render:function(h){
          return h('video',{
            ...
          })
        }
        props:{
          ...
        },
        data:{
          return{
            video: '',
            stream: '', // I need to get this using my btn_stop 
            hasUserMedia: ''
          }
        }
      }
    },
    data:()=>({
      ///...
    }),
    methods:{
      btn_stop(){
        let tracks = this.stream.getTracks()[0] // How do I access the "stream" data above on my vue-webcam component
        tracks.stop()
      }
    }
  }
</script>

Component methods are available publicly. 组件方法是公开可用的。 You can set a ref property for your component and call methods on it. 您可以为组件设置ref属性,并在其上调用方法。 For example, add a stop method to vue-webcam ... 例如,将stop方法添加到vue-webcam ...

methods: {
  stop () {
    this.stream.getTracks()[0].stop()
    this.$emit('stopped') // for extra points
  }
}

then in your parent component's template 然后在您的父组件的模板中

<vue-webcam ref="webcam" @stopped="someOptionalEventHandler" .../>

and in the btn_stop method... 并在btn_stop方法中...

methods: {
  btn_stop () {
    this.$refs.webcam.stop()
  }
}

While you're here, Vue component data must always be a function and preferably not an arrow function (especially if you need to refer to component instance properties). 在这里,Vue组件data 必须始终是一个函数,并且最好不是箭头函数(尤其是在需要引用组件实例属性的情况下)。 So both your data properties above should be 因此,您上面的两个data属性都应为

data () {
  return {
    // data properties
  }
}

or 要么

data: function() {
  return {
    // data properties
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM