I'm building a SPA using vue.js, I need to assign a div background-image referencing something in the following path:
I'm trying to reference src/assets/img/firstCard.jpg but for some reason it doesn't shows the image, this is how I'm binding the image:
HTML:
<a class="card">
<div
class="card__background"
v-bind:style="secondCard">
</div>
<div class="card__content">
<p class="card__category">Gratuita</p>
<h3 class="card__heading">Ademas en diferentes plataformas.</h3>
</div>
</a>
JS:
<script>
export default {
data () {
return {
thirdCard: {
'background-image': require('#/assets/img/firstCard.jpg')
},
secondCard: {
'background-image': require('#/assets/img/firstCard.jpg')
},
firstard: {
'background-image': require('#/assets/img/firstCard.jpg')
}
}
}
}
</script>
Thank you all for your time.
You can try to make method or computed property:
getUrl (img) {
return require(`#/assets/img/${img}.jpg`);
}
then call that method in data object (for background-image you need to specify url):
data () {
return {
firstCard: {
'background-image': `url(${this.getUrl('firstCard')})`
}
}
},
Related
I'm running into an issue where I'm trying to bind an object property to a ref in Vue, using the new composition API. I'm expecting the template to re-render with the new value after setting the ref value, but I'm however getting a RefImpl {} instead. How would I solve this?
<template>
<v-card>
<v-card-text class="pa-2">
<div v-for="(social, index) in socials" :key="index">
<p>{{ social.value }}</p>
</div>
</v-card-text>
</v-card>
</template>
<script>
import { onMounted, ref } from "#vue/composition-api/dist/vue-composition-api";
export default {
setup() {
const testVariable = ref(0);
const socials = [
{
value: testVariable,
}
];
onMounted(() => {
setTimeout(() => testVariable.value = 100, 1000);
});
return {
socials,
}
},
}
</script>
<style scoped></style>
Your socials variable does not unref inner refs in template. Basically what you have to do in your template is using social.value.value. So I think renaming that variable would be better to something like
const socials = [
{
variable: testVariable,
}
];
So that you could do social.variable.value.
Details from Vue docs:
Note the unwrapping only applies to top-level properties - nested access to refs will not be unwrapped: Read More
Looks like your code works:
const { onMounted, ref } = Vue
const app = Vue.createApp({
setup() {
const testVariable = ref(0);
const socials = [{ value: testVariable, }];
onMounted(() => {
setTimeout(() => testVariable.value = 100, 1000);
});
return { socials, }
},
})
app.mount('#demo')
<script src="https://unpkg.com/vue#3.2.29/dist/vue.global.prod.js"></script>
<div id="demo">
<div v-for="(social, index) in socials" :key="index">
<p>{{ social.value }}</p>
</div>
</div>
I am new to vue.js and currently I am building an app for learning purposes.
What I want to do:
I have a parent component which has a bunch of buttons with different id's.
The child component will wait for those id's to be sent by the parent and it will decide what to display based on the id. Thats all.
I wont post the full code because it's too large but I have tried a bunch of stuff like props and state but honestly it is so confusing.
I come from React background and I am still confused.
Parent component
<template>
<button id="btn1">Show banana</button>
<button id="btn2">Show orange</button>
</template>
<script>
export default {
name: 'Parent',
data: function {
//something
},
props: {
// ?????
}
};
</script>
**Child component**
<template>
<p v-html="something.text">
</template>
<script>
export default {
name: 'Child',
data: function() {
something: ''
if(id from parent === id I want) {
something = object.withpropIneed
}
},
};
</script>
You need to map the data from parent and pass it to child, thats it!
In example i make passing a html string and binding that html received through 'fromParentHtml' prop mapped on child, so inside child component 'this.fromParentHtml' pass to exists because it is defined in props and every time you click in parent button executes the 'show' function and change the value from passed prop to child through parent 'html' data .. =)
<template>
<div>
Current html sent to child '{{html}}'
<br>
<button #click="show('banana')">Banana</button>
<button #click="show('orange')">Orange</button>
<button #click="show('apple')">Apple</button>
<!-- Create child component -->
<child-component :fromParentHtml="html"></child-component>
</div>
</template>
<script>
export default {
name: "test3",
components: {
'child-component': {
template: "<div>Child component... <br> <span v-html='fromParentHtml'></span> </div>",
//Child component map a prop to receive the sent html from parent through the attribute :fromParentHtml ...
props: {
fromParentHtml: {
required: true,
type: String
}
}
}
},
data(){
return {
html: ''
}
},
methods: {
show(fruit){
this.html = '<span>The fruit is ' + fruit + ' !</span>';
}
}
}
</script>
<style scoped>
</style>
If helped you please mark as correct answer! Hope it helps.
Edit 1:
Assuming you have webpack to work with single file components, to import another component just do:
<template>
<div>
<my-child-component></my-child-component>
</div>
</template>
<script>
//Import some component from a .vue file
import ChildComponent from "./ChildComponent.vue";
export default {
components: {
//And pass it to your component components data, identified by 'my-child-component' in the template tag, just it.
'my-child-component': ChildComponent
},
data(){
},
methods: {
}
}
</script>
Just for the sake of it, I think you were looking for this:
<template>
<button id="btn1" #click = "id = 1">Show banana</button>
<button id="btn2" #click = "id = 2">Show orange</button>
<child-component :childid = "id"></child-component>
</template>
<script>
import childComponent from 'childComponent'
export default {
name: 'Parent',
data () {
return {
id: 0
}
},
components: {
childComponent
}
};
</script>
**Child component**
<template>
<p v-html="something.text">
</template>
<script>
export default {
name: 'Child',
props: {
childid: String
},
data: function() {
something: ''
if(this.childid === whatever) {
something = object.withpropIneed
}
},
};
</script>
Solved my problem by taking a different approach.
I have implemented state and my component behaves exactly as I wanted to.
I found this link to be helpful for me and solved my problem.
Thank you.
I have a vue component which prints out a list of radio buttons. I have a watch on internalValue which sends the selected value to the root
I am trying to send a console.log on a click event using a method called doSomething but it is not working. Furthermore I am not getting any errors or warnings.
Load Component
Vue.component('topic', require('./components/Topicselect.vue'));
Use Component
<div class="form-group" id="topic">
<topic v-model="selectedTopic"></topic>
</div>
Initialise Vue
new Vue({
el: '#topic',
data: {
selectedTopic: null
}
});
Component
<template>
<div>
<label v-for="topic in topics" class="radio-inline radio-thumbnail" style="background-image: url('http://s3.hubsrv.com/trendsideas.com/profiles/74046767539/photo/3941785781469144249_690x460.jpg')">
<input type="radio" v-model="internalValue" :click="doSomething" name="topics_radio" :id="topic.id" :value="topic.name">
<span class="white-color lg-text font-regular text-center text-capitalize">{{ topic.name }}</span>
</label>
</div>
</template>
<script>
export default {
props: ['value'],
data () {
return {
internalValue: this.value,
topics: []
}
},
mounted(){
axios.get('/vuetopics').then(response => this.topics = response.data);
},
watch: {
internalValue(v){
this.$emit('input', v);
console.log('the value is ' + this.value);
}
},
methods: {
doSomething: function (){
console.log('doSomething is firing');
}
}
}
</script>
I have a data grid component in Vue.js, which looks a bit like the one in the official sample: http://vuejs.org/examples/grid-component.html
Based on the input data instead of pure strings sometimes I'd like to display entries "decorated" as a checkbox or a v-link component (not exclusively, I may need to render other components too, like unescaped HTML or an img).
Obviously I don't want to prepare the Grid component for all the use cases, so this is not what I'd like to do:
A sample data model to be displayed:
model = [
{
field1: 'some string',
field2: 'another string',
field3: { // this should be a checkbox
state: true
},
field4: { // this should be an <a v-link>
url: 'http://whatever',
label: 'go somewhere'
}
}
]
A relevant excerpt from the Grid component:
<template>
...
<tr v-for="entry in model">
<td>
<div v-if="typeof entry === 'object' && entry.hasOwnPropery('url')">
<a v-link="entry.url">{{ entry.label }}</a>
</div>
<div v-if="typeof entry === 'object' && entry.hasOwnProperty('state')">
<input type="checkbox" v-model="entry.state">
</div>
<div v-else>
{{ entry }}
</div>
</td>
</tr>
...
</template>
What's the Vue.js philosophy for injecting custom components as decorators? I want my Grid to be completely agnostic regarding these decorator components.
This would be a good place for a mutable component piece. You define a few different decorator components and then use your data to decide which one should be used for rendering.
Template:
<div id="app">
<ul>
<li
v-for="entry in entries"
>
<component :is="entry.type">
{{ entry.content }}
</component>
</li>
</ul>
</div>
Component:
new Vue({
el: '#app',
components: {
'blank': {
template: '<div><slot></slot></div>'
},
'green': {
template: '<div style="color: #0f0;"><slot></slot></div>'
},
'red': {
template: '<div style="background-color: #f00;"><slot></slot></div>'
}
},
computed: {
entries: function() {
return this.raw_entries.map(
function(entry) {
if (typeof entry !== "object") {
return { type: 'blank', content: entry }
}
if (!entry.hasOwnProperty('type')) {
entry.type = 'blank'
}
return entry
}
)
}
},
data: {
raw_entries: [
'Base Text',
{
type: 'green',
content: 'Green Text'
},
{
type: 'red',
content: 'Red Background'
}
]
}
})
JsFiddle Working example using lists
I am new to YUI but I veteran of JQuery UI. So this one has me stumped. I cannot get my Datatable to render with the Rest service. I have two version of the code. One that I use the captured JSON object from the service as just a data object and a local datasource. That one works fine. When I attempt to switch to the GET plugin and get it from the service. It just never renders.
My local example:
#main("Play 2.1") {
<script type="text/javascript">
YUI().use("datatable", "datasource-local", "datasource-jsonschema", "datatable-datasource", function (Y) {
var data = [
{"script":{"id":34534,
"scriptText":"234523452345234",
"modifiedDate":1367525647000,
"status":"Reviewed",
"qcDate":1367526006000,
"location":{"id":1},
"orderInfo":{"id":1,
"orderName":"Order Name",
"dealerName":"Dealer Name"}
}},
{"script":{"id":656435,
"scriptText":"36536543636365",
"modifiedDate":1367525646000,
"status":"Reviewed",
"qcDate":1367526017000,
"location":{"id":1},
"orderInfo":{"id":43534534,
"orderName":"Order Name",
"dealerName":"Dealer Name"}
}}
];
var localDataSource = new Y.DataSource.Local({source:data});
localDataSource.plug(Y.Plugin.DataSourceJSONSchema, {
schema:{
resultListLocator:"",
resultFields:[
{
key:"id",
locator:"script.id"
},
{
key:"scriptText",
locator:"script.scriptText"
},
{
key:"modifiedDate",
locator:"script.modifiedDate"
}
]
}
});
var simple = new Y.DataTable({
columns:["id", "scriptText", "modifiedDate"],
summary:"Example Summary",
caption:"Example Caption"
});
simple.plug(Y.Plugin.DataTableDataSource, {
datasource:localDataSource
});
simple.render("#dataGrid");
simple.datasource.load();
});
</script>
<span id="listView">
<div id="dataGrid" style="height: 95%;width: 100%;"></div>
</span>
<div id="dataCheckArea">
<h3>RAW DATA AREA</h3>
<ul>
#records.map {record =>
<li>#record.toString</li>
}
</ul>
</div>
}
My REST Service example:
#main("Welcome to Play 2.1") {
<script type="text/javascript">
YUI().use("datatable", "datasource-get", "datasource-jsonschema", "datatable-datasource", function (Y) {
var dataSource = new Y.DataSource.Get({
source:"http://localhost:9000/reviewRecords?q=query"
});
dataSource.plug(Y.Plugin.DataSourceJSONSchema, {
schema:{
resultListLocator:"",
resultFields:[
{
key:"id",
locator:"script.id"
},
{
key:"scriptText",
locator:"script.scriptText"
},
{
key:"modifiedDate",
locator:"script.modifiedDate"
}
]
}
});
var dataGrid = new Y.DataTable({
columns:["id", "scriptText", "modifiedDate"],
summary:"Example Summary",
caption:"Example Caption"
});
dataGrid.plug(Y.Plugin.DataTableDataSource, { datasource:dataSource });
dataGrid.render("#dataGrid");
dataGrid.datasource.load();
});
</script>
<span id="listView">
<div id="dataGrid" style="height: 95%;width: 100%;"></div>
</span>
** edited because the original submission lost my second code block.
The problem wasn't with my javascript code. The issue was with how I was sending the response. The YUI framework expects that the response will be wrapped in a callback function. When I changed my response to give a JSONP response with the callback it all started working.
YUI.Env.DataSource.callbacks.yui_3_11_0_1_1379097239018_187([
{"script":{"id":34534,
"scriptText":"234523452345234",
"modifiedDate":1367525647000,
"status":"Reviewed",
"qcDate":1367526006000,
"location":{"id":1},
"orderInfo":{"id":1,
"orderName":"Order Name",
"dealerName":"Dealer Name"}
}},
{"script":{"id":656435,
"scriptText":"36536543636365",
"modifiedDate":1367525646000,
"status":"Reviewed",
"qcDate":1367526017000,
"location":{"id":1},
"orderInfo":{"id":43534534,
"orderName":"Order Name",
"dealerName":"Dealer Name"}
}}
])
I did this by using a JSONP call in the method response from Scala/Play 2.1
def reviewRecords(q: String, callback: String) = Action {
val reviewRecords = reviewRecordsService.currentReviewRecords
Ok(new Jsonp(callback, Json.toJson(DataTablesReturnObject(reviewRecords.size, reviewRecords.toArray)))).as("application/json")
}
I am going to edit the title of my original question to include the keywords for Play 2.1 and Scala because this ends up being a little different than a Java response.