Strategies for dynamically altering Vue component props using JavaScript

for instance:

<body>
<div id="app">
  <ro-weview id="wv" src="http://google.com"></ro-weview>
</div>

<script>
  (function () {
    Vue.component("ro-webview", {
      props: ["src"],
      template: `
<input type="text"  class="form-control" style="border-color: #ccc;outline: none; box-shadow: none !important; " :value="src"/>
<iframe :src="src"/>
</div>`
    })
  })()

  new Vue({el: "#app"})

  setVueProp("#wv", "src", "http://bing.com")
</script>

</body>

I am seeking to use #setVueProp to change the ro-webview src, how can I achieve this? I understand that by using JavaScript, I can access an iframe and change its src, but my goal is to alter the prop for the ro-webview instance.

Answer №1

You must determine the party responsible for making that change. Considering it is a property, I believe the parent should take care of it. You can assign a :src data attribute to the parent element and utilize it for making changes.

Check out this example:

<script src="https://cdn.bootcss.com/vue/2.1.8/vue.min.js"></script>

<div id="app"></div>

<script type="text/javascript">
window.addEventListener('load', function() {
  var webview = Vue.component("ro-weview", {
    props: ["src"],
    template: '<input type="text"  class="form-control" style="border-color: #ccc;outline: none; box-shadow: none !important; " :value="src"/><iframe :src="src"/></div>'
  })

  var myApp = new Vue({
    el: "#app",
    template: '<div id="app"><ro-weview :src="src"></ro-weview></div>',
    data: function() {
      return {
        src: 'http://www.google.com'
      }
    },
    methods: {
      setSrc: function(src) {
        this.src = src
      }
    },
    components: {
      'RoWebview': webview
    }
  })

    myApp.setSrc('http://www.bing.com')
})
</script>

Answer №2

Instead of using a function like setVueProp, you can create a component with multiple props and only pass the necessary props based on your specific requirements.

If necessary, you can add validation to the props, making some props mandatory while leaving others optional.

Vue.component('example', {
  props: {
    // basic type check (`null` means accept any type)
    propA: Number,
    // multiple possible types
    propB: [String, Number],
    // a required string
    propC: {
      type: String,
      required: true
    },
    // a number with default value
    propD: {
      type: Number,
      default: 100
    },
    // object/array defaults should be returned from a factory function
    propE: {
      type: Object,
      default: function () {
        return { message: 'hello' }
      }
    },
    // custom validator function
    propF: {
      validator: function (value) {
        return value > 10
      }
    }
  }
})

You are not obligated to provide all props when using this component, only the ones marked as required must always be passed.

Answer №3

For my personal app, I exclusively write JavaScript code that runs on the latest version of Chrome, allowing me to utilize ES6 syntax. The code below is designed for easy comprehension and defines a relative class for organizing component-related functions.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <script type="text/javascript" src="../node_modules/jquery/dist/jquery.js"></script>
  <script type="text/javascript" src="../node_modules/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
  <ro-webview id="wv" src="https://google.com"></ro-webview>
</div>

<script>
  (function () {
    Vue.component("ro-webview", {
      props: ["src"],
      template: `<iframe :src="src" target="_blank" style="width:100%;"/>`,
      mounted: function () {
        var thiz = this
        $(document).on("ro-wemedia.setSrc", function (e, v) {
          thiz.$set("src", v)
        })
      }
    })
  })()

  class RoWebview {
    constructor(selector) {
      this.selector = selector
    }

    setSrc(v) {
      $(this.selector).attr("src", v)
    }
  }

  new Vue({el: "#app"})
  new RoWebview("#wv").setSrc("http://bing.com")
</script>

</body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to extend a class in NestJS from another class?

I've encountered an issue while attempting to extend a class service from another class service in NestJS and utilize DI to load it in a third service. The error message I'm receiving from Nest is: Error: Nest can't resolve dependencies of ...

Which method is more appropriate for my request - GET or POST? Or should I consider

Recently, I've been exploring the world of get and post methods and could use some guidance! Within my App.js file, there is a user text input field and a submit button. I have a couple of tasks in mind for handling this information: Retrieve a str ...

Angular 1.5 - Component for fetching HTML content with dynamic data

Help needed with using Angular Component method. Developing a main html file with its main controller containing a JSON list of client data: clients: [{ "name": "John Jackson", "age": "21", "hair": "brown", }, { "name": "Janet Doe", ...

Which specific element should the userEvent.type(...) function target in order to work effectively with MUI's DesktopDatePicker TextField component?

Is there a way for me to input text into the TextField input within the MUI datepicker using react-testing-library's user-event? I've noticed that there is a mask applied to the input. I attempted to use userEvent.type(inputEl, '1') an ...

Converting a multipart form data string into JSON format

Can you help me figure out how to convert a multipart form data into a JSON object in Node.js? I've been looking for the right module but haven't had any luck so far. Here is an example of my form data: ------WebKitFormBoundaryZfql9GlVvi0vwMml& ...

What is the best way to assign a unique number to every div id that is generated?

I am currently using a django for loop to retrieve data from a query set. As the information is displayed, I would like to have each item wrapped in a div tag with a unique id that increments by 1 for every instance. Is there a way to achieve this directly ...

The functionality of opening a new tab when clicking on a link image is not functioning correctly on Mozilla, whereas it

Check out my code below: <a target="_blank" href="#" onclick="window.open('https://www.google.com','_blank');"> <img src="#{request.contextPath}/resources/img/landing-page/terdaftar-kominfo.png" /> </a> ...

Displaying both items upon clicking

Hey there, I'm having an issue where clicking on one article link opens both! <span class='pres'><img src='http://files.appcheck.se/icons/minecraft.png' /></span><span class='info'><a href=&apo ...

Utilizing HTML and Javascript for streaming audio and recording voice

Working on a new project that involves streaming audio files (mp3) and recording voice messages. Initially considered using Flash, but the challenge is making the website iPhone-friendly as per the client's request. Is there a technology available th ...

Tips for setting a threshold in a highcharts ng chart

I am struggling with setting the threshold to zero on a simple line chart using Highchart ng. According to the Highcharts API, the property should be plotOptions.series.threshold. However, despite following advice from this source, I can't seem to get ...

Utilizing MongoDB and Express to access collections within a controller

Is there a way to access the collection in the controller using mongodb and express? I came across this code snippet in the mongodb documentation db.getCollection("countries");, but how do you import the database name: db into a controller? serv ...

An observer is handed to me when I receive an array as a parameter

How can I use an array as a parameter instead of just receiving an observer? When trying to utilize the array, all I get is an observer. The data appears correctly when using console.log in the function that fetches information from the DB. Despite attem ...

issues arising from a growing css division

I am facing an issue where the tiles on my webpage expand on hover, but some of them are partially covered by neighboring tiles. How can I resolve this problem? Here is the CSS code snippet: .tile { position: absolute; width: 86px; background-color ...

Encountered a JavaScript loading error during the installation of Sourcetree on a Windows 7

Encountering an error during the installation of Sourcetree on a Windows 7 (32-bit) system. Atlassian JavaScript load error We encountered issues while trying to load scripts. Please ensure that your network settings permit downloading scripts from this ...

Enhance your website with a Bootstrap search bar that seamlessly integrates with your router by adding "?search=" to

I recently integrated a toggle search bar into the navigation bar of my Vue project's App.js. You can find the guide and code for it here: . However, I've encountered an issue where pressing "enter" or clicking the search button automatically ad ...

Utilizing arrays dynamically to generate data for a bar chart display in JavaScript

I'm currently working on generating a bar stack graph using the chart.js JavaScript library. My JavaScript array contains the following data: 0: {labels: "01/01/2020 00:00:00", data: 7433, category: "A"} 1: {labels: "01/01/2020 00:00:00", data: 774, ...

What is the most effective way to utilize an existing table in MySQL with a TypeORM entity?

While working with typeorm to connect to a mysql db, I encountered an issue where my table definition was overwriting an existing table in the database. Is there a way for me to use the entity module to fully inherit from an existing table without causin ...

When a directive generates an element, the ng-click function may not function as expected

I am developing a custom directive using angularJS. The directive is supposed to replace my custom element with pagination elements. However, the generated elements by the directive contain an ng-click attribute whose value is a function from the controlle ...

Automating the process of populating preferredCountries from intl-tel-input with database output

I am looking to dynamically populate the preferredCountries:["xx","yy","zz"] array with a function that retrieves the most frequently used country codes from a MySQL database, listing them in descending order of usage and including those with a count of at ...

Is it possible to pass a component into a dialogue box in material-ui using React?

Hello, I am currently facing an issue with displaying a chart component within a dialogue box. Despite having the code in place, the chart is not rendering inside the dialogue box as expected. Unfortunately, due to the complexity of the code, I am unable t ...