简体   繁体   中英

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. 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. For example, add a stop method to 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...

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). So both your data properties above should be

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

or

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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